WIth Nginx do I have to add a content-security-policy to every location block?

Environment: Nginx, Node.js, Digital Ocean Droplet

The docs for the add_header directive indicate that it can be used in an http, server or location context.

However when I add my content-security-policy to either the http or server context it isn't detected when I test it at https://csp-evaluator.withgoogle.com/ or https://securityheaders.com/.
When I add it to a location block both sites detect it.

Example header:

add_header content-security-policy "default-src 'self';"

My nginx.conf has 5 location blocks, one being used as a proxy. Do I need to add content-security-policy to every block or is there a better way?

location ~* \.(jpg|png|svg|webp|ico)$ { }
location ~* \.(css)$ { }
location ~* \.(htm|html)$ { }
location ~* \.(js)$ { }
location / {
    proxy_pass http://127.0.0.1:9999;
}

Also do I need to add all of my other main security headers to each block? It seems redundant but if that's the only way to secure the site I'll do it.

  • feature-policy
  • permissions-policy
  • referrer-policy
  • strict-transport-security
  • x-content-type-options

The add_header directive has an interesting property. From the documentation:

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.

This means if you are adding other headers in one of those location blocks, then any add_header directives from the server or http blocks would need to be repeated.

Consider using included files to organize directives like this that you may need to repeat.