When nginx add_header don't appear


A project I'm working on requires the addition of custom http headers. As with so much of nginx's (refreshingly simple) syntax, this is trivial to achieve with the NginxHttpHeadersMoreModule:

http {
  add_header X-Backend-Server 'Windows for Workgroups 3.11';
  add_header X-Content-Type-Options 'nosniff';

Problem was, I'd reboot nginx as below, then even tried restarting, but the headers wouldn't appear.

# /usr/local/etc/rc.d/nginx reload
# /usr/local/etc/rc.d/nginx restart

The first thing to check is whether our nginx has the aforementioned module. If a test of our configs returns clean with the above directives, we do.

# nginx -t

Despite the configs being reported clean, the headers still didn't appear. I was about ready to start hitting my own head–er against the wall–er.

Not to get all Malcolm Gladwell on you again, but turns out nginx only processes the deepest directives. Because I'd defined a header in a lower block, the higher ones weren't appearing. An example illustrates this:

http { 
  add_header X-Wont-Appear 'sadface';
  server {
    add_header X-Will-Appear 'yay!';

I heard you like logic errors, so I put a directive in your directive so the original is discarded. It would be useful if nginx reported this; maybe NGINX Plus does ;).

Author bio and support


Ruben Schade is a technical writer and infrastructure architect in Sydney, Australia who refers to himself in the third person. Hi!

The site is powered by Hugo, FreeBSD, and OpenZFS on OrionVM, everyone’s favourite bespoke cloud infrastructure provider.

If you found this post helpful or entertaining, you can shout me a coffee or send a comment. Thanks ☺️.