ChocoDeveloper
ChocoDeveloper

Reputation: 14608

How to avoid duplication of add_header directives in nginx?

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?

Upvotes: 5

Views: 4568

Answers (2)

Quinn Comendant
Quinn Comendant

Reputation: 10586

That's how nginx add_header works. 🤕

Another solution is to use the unofficial nginx module ngx_headers_more instead. It allows setting headers with the expected behavior, among other features. It's not for everyone, because it's not distributed with nginx (although it is available in Debian/Ubuntu via the nginx-extras package), and it also requires updating existing configurations.

Upvotes: 1

Daniel
Daniel

Reputation: 4745

Use include in each location in include shared headers (this must be duplicated but only needs to be updated in the included config not each block individually).

Upvotes: 6

Related Questions