Score:0

Force nginx to send HSTS headers for all locations

bd flag

I have a quite complicated nginx configuration where many different services expose their endpoints, with many different location{} blocks.

I don't have much control on all these configurations (because many teams add their own conf), but I'd like to add the HSTS header in all responses from nginx.

Naively I added a

add_header Strict-Transport-Security "max-age=7776000; includeSubDomains" always;

in my default conf for all server{} instances.

But I suffer from the issue where the last add_header block wins over my default conf. Any location that has a add_header in their conf will not send my HSTS header.

I.E:

[... snip ...]
server {
  listen 443 ssl;
  server_name preference.{{ domain }}; 
  add_header Strict-Transport-Security "max-age=7776000; includeSubDomains" always; # i can easily add this                                               
  error_log       /var/log/nginx/preference_error.log;
  access_log      /var/log/nginx/preference_access.log main;


  # / serves front -> proxy_pass to front container
  location / {
    expires off;
    add_header Cache-Control no-cache; # these two add_header directive "erase" my hsts header
    add_header X-Robots-Tag "noindex, nofollow";

    # proxy headers
    proxy_set_header host preference.{{ domain }};
    proxy_set_header X-Forwarded-Proto "https";
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-SSL-CERT $ssl_client_cert;
    proxy_set_header X-Robots-Tag "noindex, nofollow";
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";

    # pass to backend
    proxy_pass http://preference_upstreams/;
  }
}

Is there a way to force ALL servers/locations in nginx to add this header without manually adding it to all location where an add_header directive is present?

sv flag
You are asking for a solution that isn't supported by Nginx by default. As per https://nginx.org/r/add_header ... // There could be several add_header directives. These directives are inherited from the previous configuration level **if and only if** there are no add_header directives defined on the current level. // One alternative way is https://github.com/openresty/headers-more-nginx-module . Another way is https://nginx.org/r/js_header_filter . Good luck.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.