Welcome! Log In Create A New Profile

Advanced

Adding different headers for different requests

Posted by rsckp 
Adding different headers for different requests
June 21, 2018 05:08AM
Hi all.

So far my config has looked like this:
- adding some haders globally in http block
- then, if necessary, adding / removing some additional headers in location blocks for certain sites (server blocks)
- usually the headers added / removed are the same for all sites, ie. adding extra headers for static files (so the configuration gets repeated throughout sites)

Example:

http {
add_header xxx;

server {
location / {
}
location ~* \.(svg)$ {
add_header xyz;
}
}

server {
location / {
}
}

server {
location / {
}
location ~* \.(svg)$ {
add_header xyz;
}
}
}

Sadly, the more sites, the harder it gets to keep with multiple locations, especially considering the configuration is repeated. So I'd like to make some changes and to go with something like this:

http {
if request = ~* \.(svg)$
add_header xyz;
else
add_header xxx;

server {
location / {
}

server {
location / {
}
}

server {
location / {
}
}

The problem is that location directive cannot be used in http block. I'm thinking about constructing some IF, although don't know how should I approach this. Any ideas?

Thanks in advance!
Re: Adding different headers for different requests
June 21, 2018 08:29AM
After some research I see that I cannot use if directive in http context, it can only be used on "lower" levels, so in server or location. However, if together with add_header can only be used in location context. So it's not perfectly flexible for me - in this scenario I can configure my headers the way I want (see example below), but would still need to manually include the config file in **every** location.

add_header xxx;

if ($uri ~* \.(png)$) {
add_header xyz;
}

I'd love to hear any ideas that would help me keep my header configuration within http context (best-case scenario) or server context (if http is not possible).
Sorry, only registered users may post in this forum.

Click here to login

Online Users

Guests: 174
Record Number of Users: 8 on April 13, 2023
Record Number of Guests: 421 on December 02, 2018
Powered by nginx      Powered by FreeBSD      PHP Powered      Powered by MariaDB      ipv6 ready