Why this happens
add_header (along with proxy_set_header and fastcgi_param) is an array directive in nginx: it inherits from http to server and from server to location only as long as the lower level defines none of the same directive (Config anatomy). The moment a location contains even one add_header, the parent list is discarded completely.
Before and after
# Bad: X-Frame-Options disappears on /assets/
server {
add_header X-Frame-Options "DENY" always;
location ^~ /assets/ {
add_header Cache-Control "public, max-age=31536000, immutable" always;
}
}
# Good: shared headers live in snippets/headers.conf, included in both blocks
server {
include snippets/headers.conf;
location ^~ /assets/ {
include snippets/headers.conf;
add_header Cache-Control "public, max-age=31536000, immutable" always;
}
}
How to check
curl -sI -H "Host: example.org" http://127.0.0.1/assets/app.css | grep -iE '^(x-frame|cache-control)'
# X-Frame-Options: DENY
# Cache-Control: public, max-age=31536000, immutable
If it doesn’t work
The home page has CSP and X-Frame-Options headers, while /assets/ and /images/ don’t
- Cause
- Adding
add_header Cache-Controlinsidelocation ^~ /assets/stopped it from inheriting theadd_headerlist fromserver. - Fix
- Add
include snippets/headers.conf;insidelocation ^~ /assets/next toCache-Control.
Security headers appear on 200 OK, then vanish on 404 and 500
- Cause
add_headeris missing thealwaysparameter; without it the directive applies only to successful responses and redirects.- Fix
- Append
alwaysto the end of every line:add_header X-Frame-Options "DENY" always;.