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.
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
nginxOne fileEvery header with always in one snippet.
HSTSIn stagesmax-age from 300 seconds up to a year.
CSPReport-OnlyA nonce from nginx and violation reports.
ResultEnforcementThe 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
Header
What it protects against
Value
Strict-Transport-Security
a downgrade to HTTP and eavesdropping on public networks
running a file as a script or style despite the wrong MIME type
nosniff
Referrer-Policy
sending full page addresses to other domains
strict-origin-when-cross-origin
Permissions-Policy
embedded scripts using the camera, microphone and location
camera=(), microphone=(), geolocation=()
X-Frame-Options, frame-ancestors
embedding 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.
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;}
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;
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>
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
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;}
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.
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.
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-2
The enforced policy
The same policy as in Report-Only, with a new nonce on every response.
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.
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.
An enforced frame-ancestors with the partner's address overrides X-Frame-Options.
Frequently asked questions
The questions that come up with this setup.
01
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.
02
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.
03
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.
04
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.
05
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.
06
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.
07
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.
Penetration tests of web apps to OWASP with a report and an NDA, from PLN 1,799. The Pro package adds API tests, source code analysis and a retest after fixes.
SPF, DKIM and DMARC step by stepAn SPF record within the lookup limit, a DKIM key from openssl, DMARC with reports and the road to p=reject.
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.