35

What was (could be) the rationale behind Nginx's decision to only inherit add_header statements from the lowest level that has any?

For instance:

server {
    server_name example.com;
    root my/root;

    listen 443 ssl;

    ssl_certificate         my.cert;
    ssl_certificate_key     my.key;

    add_header  Strict-Transport-Security "max-age=31536000; includeSubdomains; preload" always;
    add_header  X-Frame-Options SAMEORIGIN;
    add_header  X-Content-Type-Options nosniff;
    add_header  Content-Security-Policy: default-src 'self' https:;

    location ~* \.(gif|jpeg|jpg|png|css|js|ico|txt)$ {
        add_header Cache-Control "public, max-age=86400";
    }
}

None of those security-related headers are added to the assets which match the location block, dedicated to increasing cache time, just because it adds another header.

The fix would be to duplicate all add_header directives into the block which seems counter intuitive to how the rest of Nginx works, e.g. the root directive.

The behaviour is documented here:

There could be several add_header directives. These directives are inherited from the previous level if and only if there are no add_header directives defined on the current level.

http://nginx.org/en/docs/http/ngx_http_headers_module.html#add_header

I guess there is a good explanation and I'm curious about what it is.

Thomas Jensen
  • 2,635
  • 25
  • 38
  • 5
    Did you ever find an answer to this question? I just stumbled across your question when I was about to ask the exact same thing. I'm using it for almost the exact same setup. – orokusaki Aug 02 '19 at 14:54
  • @orokusaki, I'm afraid not. – Thomas Jensen Aug 05 '19 at 11:20
  • 1
    Maybe the motivation was that it should be consistent with other array-type directives. See https://stackoverflow.com/a/32126596 . A solution could be to [include](https://nginx.org/en/docs/ngx_core_module.html#include) `add_header` lines where needed. – ominug Mar 17 '20 at 23:21
  • [Martin Fjordvald: Understanding the Nginx Configuration Inheritance Model (archived)](https://archive.is/mE8du). [original](http://blog.martinfjordvald.com/2012/08/understanding-the-nginx-configuration-inheritance-model/) – ominug Mar 19 '20 at 13:34
  • I reckon because it'll be much harder to "remove" certain inherited headers... Also, I suggest using a separate `.conf` file and including that if you have too many repetitive headers. – Nikolay Dimitrov Feb 24 '23 at 02:31

1 Answers1

1

understood - nginx is not inheriting add_header directives -> my solution is separate config file included in every location... and not defining add_header in server level.

tomas
  • 669
  • 2
  • 11
  • 23