Posted by

Nginx Security Headers: Add HSTS, CSP and nosniff Without the add_header Inheritance Trap

After you set up HTTPS on Nginx, the next quick security win is HTTP security headers. These are short response headers that tell the browser how to treat your site. For example, they can force HTTPS, stop MIME-type guessing, block other sites from framing your pages, and limit which scripts may run.

They take a few minutes to add. However, Nginx has one well-known trap: the way add_header is inherited. Because of it, many servers send the headers on some pages and silently drop them on others. This guide shows a safe setup on Ubuntu or Debian, explains the trap, and shows how to test the result.

Before you start

  • Nginx is installed and your site already works over HTTPS. If not, see our guide on free HTTPS with Certbot and Let's Encrypt first.
  • You have sudo access and can run nginx -t.
  • You can reach the server another way (console or a second SSH session) in case a change breaks something.

The headers, in short

HeaderStarting valueWhat it does
Strict-Transport-Securitymax-age=31536000Tells the browser to use only HTTPS for this host for the given number of seconds (here, one year).
X-Content-Type-OptionsnosniffStops the browser from guessing a file's type, which blocks some script-injection tricks.
X-Frame-OptionsSAMEORIGIN or DENYControls whether other sites may show your pages in a frame (protection against clickjacking).
Referrer-Policystrict-origin-when-cross-originLimits how much of your URL is sent to other sites when visitors follow links.
Permissions-Policycamera=(), microphone=(), geolocation=()Turns off browser features your site does not use.
Content-Security-PolicyDepends on your siteLists where scripts, styles, images and frames may load from. The strongest header, and the one that needs the most testing.

The add_header inheritance trap

The official Nginx documentation for the ngx_http_headers_module says that add_header directives are inherited from the previous configuration level if and only if there are no add_header directives on the current level.

In practice, this means a single add_header inside a location block cancels every header set in the server or http block for that location. Look at this example:

server {
    add_header X-Content-Type-Options "nosniff" always;
    add_header Strict-Transport-Security "max-age=31536000" always;

    location /static/ {
        add_header Cache-Control "public, max-age=86400";
        # This location now sends ONLY Cache-Control.
        # nosniff and HSTS are gone here.
    }
}

The fix used in this guide is simple: keep all security headers in one snippet file and include it again in every block that has its own add_header.

The always flag

By default, Nginx adds a header only to responses with certain status codes (200, 201, 204, 206, 301, 302, 303, 304, 307 and 308). Error pages such as 404 or 500 do not get the header. If you add the always parameter, Nginx adds the header to every response, whatever the status code. Use always for security headers.

Step 1: Create a snippet file

Create /etc/nginx/snippets/security-headers.conf:

sudo nano /etc/nginx/snippets/security-headers.conf

Start with these values:

# HTTPS only for one year. Add includeSubDomains only when
# every subdomain works over HTTPS (see below).
add_header Strict-Transport-Security "max-age=31536000" always;

add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;

# Test CSP first in report-only mode (see Step 4).
add_header Content-Security-Policy-Report-Only "default-src 'self'; frame-ancestors 'self'; object-src 'none'; base-uri 'self'" always;

Step 2: Include it in your HTTPS server block

Open your site file, for example /etc/nginx/sites-available/example.com, and add the include to the server block that listens on port 443. Also add it to every location that has its own add_header:

server {
    listen 443 ssl;
    server_name example.com www.example.com;

    include snippets/security-headers.conf;

    location /static/ {
        add_header Cache-Control "public, max-age=86400";
        include snippets/security-headers.conf;   # repeat it here
    }
}

While you are in the config, also hide the exact Nginx version from the Server header and error pages. Put this in the http block of /etc/nginx/nginx.conf (Ubuntu and Debian ship it as a commented-out line):

server_tokens off;

This does not fix any bug, but it gives attackers less free information. Keeping Nginx updated is what actually protects you.

Step 3: Test and reload

sudo nginx -t
sudo systemctl reload nginx

Only reload when nginx -t reports that the syntax is ok and the test is successful. Then check the headers from your own computer:

curl -sI https://example.com/
curl -sI https://example.com/static/some-file.css
curl -sI https://example.com/page-that-does-not-exist

Every response, including the 404, should show the same security headers. If one path is missing them, look for an add_header in that location block and include the snippet there too.

Step 4: Roll out Content-Security-Policy safely

A strict CSP can break a site that loads scripts, fonts or analytics from other domains. For that reason, the snippet starts with Content-Security-Policy-Report-Only. In this mode, the browser does not block anything. It only reports violations in the developer console.

  1. Open your main pages with the browser developer tools open and read the CSP messages in the Console.
  2. Add each trusted source you really need, for example script-src 'self' https://www.googletagmanager.com.
  3. When the console is clean, rename the header to Content-Security-Policy to enforce it.

The frame-ancestors directive in CSP is the modern way to control framing. Keep X-Frame-Options as well for older browsers. Also remember that report-only mode blocks nothing, so until you enforce CSP, X-Frame-Options is what actually stops other sites from framing your pages.

Step 5: Strengthen HSTS when you are ready

HSTS is powerful because the browser remembers it. If you later break HTTPS, visitors cannot click through the warning until max-age runs out. So build it up in stages:

  1. Start with a short value such as max-age=300 (five minutes) and check that the whole site works.
  2. Raise it to max-age=31536000 (one year).
  3. Add includeSubDomains only when every subdomain, including internal ones, works over HTTPS.
  4. Consider the browser preload list (hstspreload.org) last. Its requirements include a valid certificate, a redirect from HTTP to HTTPS on the same host, and an HSTS header with at least one year of max-age, includeSubDomains and preload. Removal from the list is slow, so do not submit a domain you are unsure about.

Send HSTS only on HTTPS responses. Browsers ignore it over plain HTTP, so you do not need it in the port 80 server block that only redirects.

Common mistakes

  • Headers missing on some paths. This is the inheritance trap. Search your config with grep -rn add_header /etc/nginx/ and include the snippet in each block you find.
  • Headers missing on error pages. Add the always parameter.
  • Duplicate headers. If Nginx is a reverse proxy and the application also sends a header such as X-Frame-Options, the browser can receive two different values. Remove it in one place, or hide the backend copy with proxy_hide_header X-Frame-Options;.
  • Still setting X-XSS-Protection. Modern browsers have removed this XSS filter, and the OWASP HTTP Headers Cheat Sheet advises against enabling it. Use a Content-Security-Policy instead.
  • Enforcing CSP without testing. Always use report-only mode first.

Check your score

Besides curl -I, you can scan a public site with the HTTP Observatory on MDN (developer.mozilla.org/en-US/observatory). It grades the headers and explains each finding. Run it again after every change.

Summary

  • Put all security headers in one snippet and use always on each of them.
  • Include the snippet in every block that has its own add_header, because Nginx does not merge them.
  • Test with nginx -t before reloading, then check normal, static and 404 responses with curl -I.
  • Roll out CSP in report-only mode first, and raise HSTS step by step.

Sources

  • Nginx documentation: Module ngx_http_headers_module (add_header, inheritance and the always parameter) and the server_tokens directive, nginx.org
  • Nginx documentation: proxy_hide_header, Module ngx_http_proxy_module, nginx.org
  • RFC 6797: HTTP Strict Transport Security (HSTS), IETF
  • HSTS preload list submission requirements, hstspreload.org
  • MDN Web Docs: Strict-Transport-Security, Content-Security-Policy, X-Content-Type-Options, X-Frame-Options, Referrer-Policy, Permissions-Policy and HTTP Observatory
  • OWASP HTTP Headers Cheat Sheet, OWASP Cheat Sheet Series