Home > Mobile >  Add HSTS header to my domain but NOT add the header if the request is an API::P request
Add HSTS header to my domain but NOT add the header if the request is an API::P request

Time:05-26

I used the Negated Regular Expressions in location but it does add the header but removes everything else that existed before. Even if I add it doesn’t consider the rest only hsts. I am not sure what is the best way to do this. add a header for anything else but "don't add this HSTS header if we're on API::P".

location ~ (?!^/p/) {
  add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
}

or

location ~ ^(/p/) {
  add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
}

Here is the logic that I have in mind.

if location == "/p/":
    pass
else:
    add_header ...HSTS...

CodePudding user response:

Because of performance considerations, avoid using regex whenever possible. Either use two locations duplicating everything else that cannot be moved one level up:

location / {
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    ... common configuration
}
location /p/ {
    ... common configuration
}

or use the map block (however this actually will make at least one PRCE library call):

map $uri $hsts {
    ~^/p/    "";
    default  "max-age=31536000; includeSubDomains";
}
server {
    ...
    add_header Strict-Transport-Security $hsts always;
    ...
}

If evaluated variable used in the add_header directive will be empty, nginx won't add a header with an empty value - instead it won't add such a header at all.

For the two-locations configuration, every request started with /p/ will be handled with the location /p/ { ... }, and every other request will be handled with the location / { ... }. There is absolutely no need to use any regex locations for this particular case.

Please note that add_header directives are inherited from the previous configuration level if and only if there are no add_header directives defined on the current level.

  • Related