basforge

Search titles, text and the “If it doesn’t work” cases.

    RU

    add_header in location — wipes all add_header directives from server

    A single add_header Cache-Control inside a location silently drops every Strict-Transport-Security, CSP, and X-Frame-Options set at the server level. Move shared security headers into a snippet and pull them in with include inside every such location.

    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-Control inside location ^~ /assets/ stopped it from inheriting the add_header list from server.
    Fix
    Add include snippets/headers.conf; inside location ^~ /assets/ next to Cache-Control.

    Security headers appear on 200 OK, then vanish on 404 and 500

    Cause
    add_header is missing the always parameter; without it the directive applies only to successful responses and redirects.
    Fix
    Append always to the end of every line: add_header X-Frame-Options "DENY" always;.