Nginx – How to avoid duplication of add_header directives in nginx

http-headersnginx

The documentation says this:

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

My problem is that I have several location blocks that I want to cache, like this one:

add_header X-Frame-Options SAMEORIGIN;
add_header Strict-Transport-Security "max-age=31536000; includeSubdomains;";

location ~ ^/img/(.*)\.(png|jpg|jpeg|gif|bmp)$ {
    expires 1w;
    add_header Cache-Control public;
}

But that will make me lose all the headers declared outside of the block. So apparently the only way is duplicating those headers on every location block, eg:

add_header X-Frame-Options SAMEORIGIN;
add_header Strict-Transport-Security "max-age=31536000; includeSubdomains;";

location ~ ^/img/(.*)\.(png|jpg|jpeg|gif|bmp)$ {
    expires 1w;
    add_header Cache-Control public;
    add_header X-Frame-Options SAMEORIGIN;
    add_header Strict-Transport-Security "max-age=31536000; includeSubdomains;";
}

Doesn't seem right. Any ideas?

Best Answer

You're after the ngx_headers_more module: https://www.nginx.com/resources/wiki/modules/headers_more/

And yes, the behaviour of add_header is really irritating :)