How to set security headers in nginx: HSTS, CSP and the rest, step by step

You collect the headers in one file with the always parameter, roll HSTS out in stages and start CSP in Report-Only with a nonce that nginx generates. Along the way you avoid the add_header inheritance trap. We ran the configuration in nginx 1.31.6 in Docker and checked it with curl and in Chromium 153.

What you will do

Headers do not fix bugs in the code, but they close whole classes of attacks. HSTS stops a downgrade to HTTP, CSP blocks scripts that are not on the list, frame-ancestors stops the page from being embedded in someone else's frame, and nosniff turns off file type guessing. After this guide you have them in one file, on every response, error pages included.

Most of the trouble comes from nginx itself: add_header in a location block wipes every header inherited from the server block. We show it on a real response, along with two ways around it.

Level
intermediate
Code
nginx
Steps
8 steps
  1. nginx One file Every header with always in one snippet.
  2. HSTS In stages max-age from 300 seconds up to a year.
  3. CSP Report-Only A nonce from nginx and violation reports.
  4. Result Enforcement The same policy starts blocking.

What you need

  • Access to the nginx configuration

    Permission to edit files in /etc/nginx and to reload the service. On hosting without nginx access you can set some headers in the panel, if the host allows it.

  • HTTPS on every subdomain

    includeSubDomains in HSTS tells the browser to use HTTPS for subdomains too, internal ones included. Check them before the first stage in step 3.

  • A list of the site's scripts, styles and frames

    Analytics, chat, maps, payments, video: CSP must know every source. Report-Only mode shows the ones you forget.

  • nginx 1.29.3 or newer for add_header_inherit

    On older versions the include-in-every-location approach works. The distribution repositories carry older versions: Debian 13 has 1.26.3, Ubuntu 24.04 1.24.0 and Ubuntu 26.04 1.28.3. The official nginx:alpine image we tested on has 1.31.6.

The headers and values in this guide

HeaderWhat it protects againstValue
Strict-Transport-Securitya downgrade to HTTP and eavesdropping on public networksmax-age=31536000; includeSubDomains
Content-Security-Policyinjected scripts (XSS)script-src 'nonce-$request_id' 'strict-dynamic'; object-src 'none'; base-uri 'none'
X-Content-Type-Optionsrunning a file as a script or style despite the wrong MIME typenosniff
Referrer-Policysending full page addresses to other domainsstrict-origin-when-cross-origin
Permissions-Policyembedded scripts using the camera, microphone and locationcamera=(), microphone=(), geolocation=()
X-Frame-Options, frame-ancestorsembedding the page in someone else's frame (clickjacking)DENY, frame-ancestors 'none'

Step by step

Each step with commands to copy. The list on the left shows where you are.

01

Collect the headers in one file

Without the always parameter nginx adds a header only to 200, 201, 204, 206, 301, 302, 303, 304, 307 and 308 responses. A 404 or 500 page is then left unprotected, which is why every line ends with always.

Referrer-Policy strict-origin-when-cross-origin is the browsers' default according to MDN, but setting it explicitly also covers browsers with a different default. Permissions-Policy with an empty list () switches a feature off for the page and every frame, so list only the ones the site does not use. CSP is in Report-Only for now, see step 4.

/etc/nginx/snippets/security-headers.conf
# Shared security headers. always: also on 404 and 500.add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;add_header X-Content-Type-Options "nosniff" always;add_header Referrer-Policy "strict-origin-when-cross-origin" always;add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;add_header X-Frame-Options "DENY" always;add_header Reporting-Endpoints 'csp="https://example.com/csp-reports"' always;add_header Content-Security-Policy-Report-Only "default-src 'self'; script-src 'nonce-$request_id' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; report-uri /csp-reports; report-to csp" always;
nginx -t in the test container
Command
docker exec guides-nginx nginx -t
Output
nginx: the configuration file /etc/nginx/nginx.conf syntax is oknginx: configuration file /etc/nginx/nginx.conf test is successful
Command
docker exec guides-nginx nginx -s reload
02

Include the file in the server block and check with curl

You include the snippet in the HTTPS server blocks. Browsers ignore HSTS sent over HTTP, and RFC 6797 forbids sending it there, so the port 80 block only redirects. The /assets/ location has its own add_header, so it includes the snippet again, for the reason explained in step 6.

curl -I fetches only the headers. In the test --resolve sent the request to the container and -k skipped the self-signed certificate. On a real server curl -sI https://yourdomain.com/ is enough. The headers are on the home page and on the 404 page.

/etc/nginx/conf.d/example.com.conf
# CSP reports go to a separate file, with the request body as JSONlog_format csp escape=json '{"time":"$time_iso8601","report":"$request_body"}';server { listen 80; server_name example.com www.example.com; return 301 https://example.com$request_uri;}server { listen 443 ssl; server_name www.example.com; ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; include /etc/nginx/snippets/security-headers.conf; return 301 https://example.com$request_uri;}server { listen 443 ssl; server_name example.com; ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; root /var/www/example.com; include /etc/nginx/snippets/security-headers.conf; location / { # the same nonce goes into the CSP header and into the HTML nonce attributes sub_filter_once off; sub_filter "__CSP_NONCE__" $request_id; try_files $uri $uri/ =404; } location /assets/ { # a location's own add_header turns off inheritance, so the headers are included again include /etc/nginx/snippets/security-headers.conf; add_header Cache-Control "public, max-age=31536000, immutable" always; } location = /csp-reports { limit_except POST { deny all; } access_log /var/log/nginx/csp.log csp; proxy_pass http://127.0.0.1:8099; }}server { listen 127.0.0.1:8099; return 204;}
curl -I, nginx 1.31.6
Command
curl -skI --resolve example.com:443:127.0.0.2 https://example.com/
Output
HTTP/1.1 200 OKServer: nginx/1.31.6Strict-Transport-Security: max-age=31536000; includeSubDomainsX-Content-Type-Options: nosniffReferrer-Policy: strict-origin-when-cross-originPermissions-Policy: camera=(), microphone=(), geolocation=()X-Frame-Options: DENYReporting-Endpoints: csp="https://example.com/csp-reports"Content-Security-Policy-Report-Only: default-src 'self'; script-src 'nonce-ca15b121beddd40d9b02fde88cccb72d' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; report-uri /csp-reports; report-to csp
Command
curl -skI --resolve example.com:443:127.0.0.2 https://example.com/no-such-page
Output
HTTP/1.1 404 Not FoundStrict-Transport-Security: max-age=31536000; includeSubDomainsX-Content-Type-Options: nosniffReferrer-Policy: strict-origin-when-cross-originPermissions-Policy: camera=(), microphone=(), geolocation=()X-Frame-Options: DENYReporting-Endpoints: csp="https://example.com/csp-reports"Content-Security-Policy-Report-Only: default-src 'self'; script-src 'nonce-5a8ceb0433c25707d0c6fbd97c0fcd02' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; report-uri /csp-reports; report-to csp
03

Roll HSTS out in stages

After a first visit with HSTS the browser will not connect to the domain over HTTP for max-age seconds, and with includeSubDomains to any subdomain either. If one of them has no HTTPS it stops opening, and the server cannot take that back until the time runs out. That is why hstspreload.org recommends stages: 5 minutes, a week, a month, waiting out the full max-age at each one.

The preload list built into browsers requires max-age of at least 31536000, includeSubDomains, the preload directive and HTTPS on every subdomain. hstspreload.org itself says preloading is not recommended: the gain over plain HSTS is small and removing a domain from the list takes months. github.com uses preload, as the output shows.

/etc/nginx/conf.d/example.com.conf
# stage 1, 5 minutes: check that every subdomain works over HTTPSadd_header Strict-Transport-Security "max-age=300; includeSubDomains" always;# stage 2, a week# add_header Strict-Transport-Security "max-age=604800; includeSubDomains" always;# stage 3, a month# add_header Strict-Transport-Security "max-age=2592000; includeSubDomains" always;# goal, a year: the value from security-headers.conf# add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
curl: local nginx and github.com
Command
curl -skI --resolve hsts.example.com:443:127.0.0.2 https://hsts.example.com/ | grep -i strict
Output
Strict-Transport-Security: max-age=300; includeSubDomains
Command
curl -sI https://github.com/ | grep -i -E "^(strict-transport|x-frame|x-content-type|referrer-policy)"
Output
strict-transport-security: max-age=31536000; includeSubdomains; preloadx-frame-options: denyx-content-type-options: nosniffreferrer-policy: origin-when-cross-origin, strict-origin-when-cross-origin
04

Start CSP in Report-Only with a nonce

The Content-Security-Policy-Report-Only header blocks nothing, it only reports violations. In the meantime you collect reports and add the missing sources while the site keeps working as before.

script-src 'nonce-...' 'strict-dynamic' lets through only scripts with a valid nonce attribute and the ones they load themselves. The CSP specification requires a new nonce on every response and recommends at least 128 bits. The nginx $request_id variable is 16 random bytes in hex, exactly 128 bits. sub_filter puts the same value into the nonce attributes in the HTML, so the header and the page always match.

google.com does the same: its home page policy is served in Report-Only, with a nonce and 'strict-dynamic'.

/var/www/example.com/index.html
<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Test CSP</title><!-- nginx puts into the nonce attribute the same $request_id it sends in the CSP header --><script nonce="__CSP_NONCE__">window.withNonce = true;</script><!-- script without a nonce: in Report-Only it goes into the report, once CSP is enforced it is blocked --><script>window.withoutNonce = true;</script></head><body><h1>Test CSP</h1></body></html>
curl: local nginx and google.com
Command
curl -sk -D - --resolve example.com:443:127.0.0.2 https://example.com/ | grep -o 'nonce[-="]*[0-9a-f]\{32\}'
Output
nonce-684e35edf48cbb6b67c743c40ce999bbnonce="684e35edf48cbb6b67c743c40ce999bb
Command
curl -sI https://www.google.com/ | grep -i -E "^(content-security|x-frame)"
Output
content-security-policy-report-only: object-src 'none';base-uri 'self';script-src 'nonce-XIUoedcxtIEe6ZGA5piCcw' 'strict-dynamic' 'report-sample' 'unsafe-eval' 'unsafe-inline' https: http:;report-uri https://csp.withgoogle.com/csp/gws/other-hpx-frame-options: SAMEORIGIN
05

Collect the violation reports

The policy has two report addresses. report-uri is the older mechanism, which MDN marks as deprecated. report-to points to a name from the Reporting-Endpoints header. Browsers that support report-to ignore report-uri, which is why MDN recommends both for now.

The /csp-reports location from step 2 accepts only POST and writes the report body to a separate log. nginx fills the $request_body variable only where proxy_pass, fastcgi_pass, uwsgi_pass or scgi_pass runs, so the request goes to a small server on 127.0.0.1:8099 that answers 204.

In Chromium the script without a nonce ran and the console reported the violation. The report arrived through report-to as a csp-violation. For that test we started Chromium with the --short-reporting-delay flag, which shortens the delay with which the browser sends report-to reports.

Chromium 153 and the report log
Command
python3 browser.py 0
Output
browser 153.0.8010.12console: Executing inline script violates the following Content Security Policy directive 'script-src 'nonce-0c005bab2841bb4cffaea55359e0a6cc' 'strict-dynamic''. Either the 'unsafe-inline' keyword, a hash ('sha256-oAeuQhcVy1+yqmBho4pG++UAyp16L9nlelxfUclo4Ls='), or a nonce ('nonce-...') is required to enable inline execution. The policy is report-only, so the violation has been logged but no further action has been taken.withNonce: TruewithoutNonce: True
Command
tail -n 1 logs/csp.log | jq -r .report | jq ".[0] | {type, url, body: (.body | {effectiveDirective, blockedURL, disposition, lineNumber})}"
Output
{ "type": "csp-violation", "url": "https://example.com/", "body": { "effectiveDirective": "script-src-elem", "blockedURL": "inline", "disposition": "report", "lineNumber": 7 }}
06

Avoid the add_header inheritance trap

The nginx documentation says it plainly: add_header directives are inherited from the previous level only when the current level has none. A single Cache-Control in location /assets/ is enough for the files in that directory to lose HSTS, CSP and the rest.

In the output old.example.com has location /assets/ with only add_header Cache-Control. The file comes back without a single security header, and the missing always means the 404 loses Cache-Control too. Step 2 shows the approach for any nginx version: the snippet included again in the location. From nginx 1.29.3 add_header_inherit merge is enough, as the new.example.com response shows.

/etc/nginx/conf.d/example.com.conf
# from nginx 1.29.3: headers from the server level are added to those from the locationadd_header_inherit merge;include /etc/nginx/snippets/security-headers.conf;location /assets/ { add_header Cache-Control "public, max-age=31536000, immutable" always;}
curl -I, the trap and the fix
Command
curl -skI --resolve old.example.com:443:127.0.0.2 https://old.example.com/assets/app.css
Output
HTTP/1.1 200 OKServer: nginx/1.31.6Content-Type: text/cssConnection: keep-aliveCache-Control: public, max-age=31536000, immutableAccept-Ranges: bytes
Command
curl -skI --resolve old.example.com:443:127.0.0.2 https://old.example.com/assets/missing.css
Output
HTTP/1.1 404 Not FoundServer: nginx/1.31.6Connection: keep-alive
Command
curl -skI --resolve new.example.com:443:127.0.0.2 https://new.example.com/assets/app.css
Output
HTTP/1.1 200 OKCache-Control: public, max-age=31536000, immutableStrict-Transport-Security: max-age=31536000; includeSubDomainsX-Content-Type-Options: nosniffReferrer-Policy: strict-origin-when-cross-originPermissions-Policy: camera=(), microphone=(), geolocation=()X-Frame-Options: DENYReporting-Endpoints: csp="https://example.com/csp-reports"Content-Security-Policy-Report-Only: default-src 'self'; script-src 'nonce-bc55327aaecbac909d8a8a4b77228692' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; report-uri /csp-reports; report-to csp
07

frame-ancestors replaces X-Frame-Options, but not straight away

The CSP specification says that an enforced frame-ancestors overrides X-Frame-Options. In Report-Only it does not: the browser still follows X-Frame-Options. So while CSP is in Report-Only, X-Frame-Options DENY stays in the snippet, and it is what protects the page.

We checked it in Chromium 153 on three frames. The frame at example.com, with frame-ancestors in Report-Only, was blocked by the X-Frame-Options header. The frame at embedded.example.com, with an enforced frame-ancestors for frame.example.org, loaded although it sends X-Frame-Options DENY. The frame at embedded-ro.example.com, with the same policy in Report-Only, was blocked by X-Frame-Options again.

The ALLOW-FROM value of X-Frame-Options is obsolete, and according to MDN modern browsers then ignore the whole header. When a partner has to embed the page, use frame-ancestors with its address.

/etc/nginx/conf.d/example.com.conf
# enforced frame-ancestors: the browser then ignores X-Frame-Optionsadd_header X-Frame-Options "DENY" always;add_header Content-Security-Policy "frame-ancestors https://frame.example.org" always;
Chromium 153, three frames on frame.example.org
Command
python3 browser.py 0
Output
console: Framing 'https://example.com/' violates the following report-only Content Security Policy directive: "frame-ancestors 'none'". The violation has been logged, but no further action has been taken.console: Refused to display 'https://example.com/' in a frame because it set 'X-Frame-Options' to 'deny'.console: Refused to display 'https://embedded-ro.example.com/' in a frame because it set 'X-Frame-Options' to 'deny'.iframe https://example.com/ -> blockediframe https://embedded.example.com/ -> loadediframe https://embedded-ro.example.com/ -> blocked
08

Switch CSP from Report-Only to enforcement

Once the reports show only violations you expect, from browser extensions for example, rename the header to Content-Security-Policy. The policy stays the same, it just blocks now. The script without a nonce stopped running, and the example.com frame is now blocked by CSP itself.

After nginx -s reload the old worker processes may still serve requests for a moment. Our first curl right after the reload returned the old header, which is why the commands include sleep 1.

/etc/nginx/snippets/security-headers.conf
add_header Content-Security-Policy "default-src 'self'; script-src 'nonce-$request_id' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; report-uri /csp-reports; report-to csp" always;
the switch and Chromium 153
Command
sed -i "s/add_header Content-Security-Policy-Report-Only /add_header Content-Security-Policy /" snippets/security-headers.confdocker exec guides-nginx nginx -t
Output
nginx: the configuration file /etc/nginx/nginx.conf syntax is oknginx: configuration file /etc/nginx/nginx.conf test is successful
Command
docker exec guides-nginx nginx -s reloadsleep 1curl -skI --resolve example.com:443:127.0.0.2 https://example.com/ | grep -i "^content-security"
Output
Content-Security-Policy: default-src 'self'; script-src 'nonce-d2eab87a321ec30276acf6bda5c39717' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; report-uri /csp-reports; report-to csp
Command
python3 browser.py 0
Output
console: Executing inline script violates the following Content Security Policy directive 'script-src 'nonce-06e3b8c6b1c3cf5523745f4b8a2f8930' 'strict-dynamic''. Either the 'unsafe-inline' keyword, a hash ('sha256-oAeuQhcVy1+yqmBho4pG++UAyp16L9nlelxfUclo4Ls='), or a nonce ('nonce-...') is required to enable inline execution. The action has been blocked.withNonce: TruewithoutNonce: False

How to check it works

We ran the configuration in the official nginx:alpine image with nginx 1.31.6 and a self-signed certificate. nginx -t passed, and curl showed the full set of headers on the home page, a file from /assets/ and the 404 page. We checked the inheritance trap and add_header_inherit merge on separate server blocks.

In Chromium 153 driven by Playwright the script without a nonce ran in Report-Only and was reported, and after the switch to enforcement it was blocked. We checked that frame-ancestors takes precedence over X-Frame-Options on three frames.

Environment
nginx 1.31.6 (nginx:alpine) in Docker, curl 8.5.0, Chromium 153 via Playwright
Result
Headers on every response, the script without a nonce blocked, the partner's frame allowed

What you should see

  • curl -sI shows every header on the home page, a static file and the 404 page.
  • The nonce in the CSP header and in the HTML is the same and changes on every request.
  • The browser console reports no CSP violations for your own scripts.
  • Reports land in the /var/log/nginx/csp.log log.
enforced CSP, Chromium 153
Command
curl -skI --resolve example.com:443:127.0.0.2 https://example.com/ | grep -i "^content-security"
Output
Content-Security-Policy: default-src 'self'; script-src 'nonce-3089ae2395759901a4a2901bf9eac1c3' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; report-uri /csp-reports; report-to csp
Command
python3 browser.py 0
Output
browser 153.0.8010.12console: Executing inline script violates the following Content Security Policy directive 'script-src 'nonce-06e3b8c6b1c3cf5523745f4b8a2f8930' 'strict-dynamic''. Either the 'unsafe-inline' keyword, a hash ('sha256-oAeuQhcVy1+yqmBho4pG++UAyp16L9nlelxfUclo4Ls='), or a nonce ('nonce-...') is required to enable inline execution. The action has been blocked.withNonce: TruewithoutNonce: Falseconsole: Framing 'https://example.com/' violates the following Content Security Policy directive: "frame-ancestors 'none'". The request has been blocked.console: Refused to display 'https://embedded-ro.example.com/' in a frame because it set 'X-Frame-Options' to 'deny'.iframe https://example.com/ -> blockediframe https://embedded.example.com/ -> loadediframe https://embedded-ro.example.com/ -> blocked
  1. 1-2
    The enforced policy

    The same policy as in Report-Only, with a new nonce on every response.

  2. 5-7
    The script without a nonce blocked

    withNonce ran, withoutNonce no longer does. Chromium also gives the script's sha256 hash in case you prefer a hash.

  3. 8-12
    The frames

    example.com blocked by frame-ancestors, the partner's frame loaded despite X-Frame-Options DENY, the Report-Only version blocked by X-Frame-Options.

Headers in a security audit

How it looks in our project

Hand it over when the site loads scripts from many services and you do not know which ones it needs, or when CSP has to protect a panel with customer data rather than a brochure site.

In a VulCode security audit, from PLN 1,799 (about EUR 400), we check TLS and the headers, meaning protocol versions, ciphers, CSP, HSTS and X-Frame-Options, together with application tests to the OWASP Top 10. You can also build a starting policy yourself in the CSP generator, which hashes a script and shows the risks.

See the service

Common errors

Symptom, cause and fix, with the number of the step where the error shows up.

StepSymptomCauseFix
01 No headers on 404 and 500 pages add_header without the always parameter. Add always to every line in the snippet.
06 Files in /assets/ without security headers add_header in a location turns off inheritance from the server block. Include the snippet in that location or set add_header_inherit merge (1.29.3+).
03 A subdomain stopped opening after HSTS went on includeSubDomains while the subdomain has no HTTPS. Give the subdomain HTTPS. Start at max-age=300 so the effects last 5 minutes.
04 Every response has the same nonce HTML with a nonce is cached by a proxy or a CDN. Turn caching off for HTML with a nonce or switch to hashes for static pages.
04 __CSP_NONCE__ stays in the HTML The sub_filter module is missing or the response is not text/html. Check nginx -V, and add sub_filter_types for other types.
07 A partner cannot embed the page X-Frame-Options DENY next to CSP in Report-Only. An enforced frame-ancestors with the partner's address overrides X-Frame-Options.

Frequently asked questions

The questions that come up with this setup.

How do I check which security headers my site sends?
With curl -I and the address of your site: the response lists every header. Check a 404 page too, because without the always parameter the headers disappear on errors; step 2 of the guide shows both tests.
Should I submit my domain to the HSTS preload list?
hstspreload.org itself does not recommend it: the gain over plain HSTS is small, because Chrome and Safari upgrade navigations to HTTPS anyway, and getting off the list takes months. It only makes sense when every subdomain, internal ones included, runs on HTTPS for good.
report-uri or report-to?
Both, for now. MDN marks report-uri as deprecated but recommends sending it next to report-to until report-to is widely supported. A browser that knows report-to ignores report-uri.
Nonce or hash?
A nonce for pages generated on every request, because nginx gives a new one with every response. A hash for static and cached pages: you compute it once from the script's content. Chromium itself prints the sha256 hash of a blocked script in the console, and the CSP generator computes it from the code.
Is X-XSS-Protection still needed?
No. MDN marks it as deprecated and non-standard and warns that in some cases it creates XSS vulnerabilities itself. CSP takes its place.
Should I hide the nginx version in the Server header?
server_tokens off; removes the version number from the Server header and from error pages. It removes no vulnerability, but it does not hand an attacker the version number.
How much does a security audit of a website or an app cost?
A VulCode security audit starts from PLN 1,799 (about EUR 400). It checks TLS and headers and tests the application to the OWASP Top 10.

Sources

The documentation and specifications we compared the commands with.

Other guides

Tools

  • CSP generator with a risk checkContent-Security-Policy (CSP) limits where a page loads scripts and styles from. Build one from a preset, hash an inline script and check the risks.
  • Base64, JWT and hashBase64 writes binary data as text. Encode and decode it, or hash text or a file with MD5, SHA-1, SHA-256, SHA-384 and SHA-512 in your browser, free.
  • Website launch checklistGenerate a website launch checklist tailored to your site: staging, redirects, robots.txt, sitemap, canonical, hreflang, structured data and Search Console.

Glossary terms

Tell us what you want to build.

A free quote comes back within an hour during working hours. You talk to the person who writes the code.