Nginx security headers: HSTS, CSP, X-Frame-Options and how to test them
Security headers tell the browser to refuse risky behaviour: loading your site over plain HTTP, being framed by another site, or running injected scripts. They are free and quick to add, and scanners check for them.
See what you send today
Request the headers of your own site.
curl -sI https://your-domain.com | grep -Ei 'strict-transport|content-security|x-frame|x-content|referrer|permissions'Add the safe headers to the server block
These do not break normal sites. always makes nginx add them on error pages too.
add_header X-Content-Type-Options "nosniff" always; add_header Referrer-Policy "strict-origin-when-cross-origin" always; add_header X-Frame-Options "SAMEORIGIN" always; add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;Add HSTS only when every subdomain works on HTTPS
HSTS makes browsers refuse HTTP for the period you set. Start with a short one and raise it later. Add includeSubDomains and preload only when you are sure.
add_header Strict-Transport-Security "max-age=300" always; # test, then 31536000Start CSP in report-only mode
A strict Content-Security-Policy can break scripts and fonts. Report-only shows what would break without breaking it.
add_header Content-Security-Policy-Report-Only "default-src 'self'; img-src 'self' data: https:; script-src 'self'" always;Watch the add_header inheritance trap
If a location block has its own add_header line, it replaces every header set above it. Repeat the headers there, or put them in one snippet you include in each block.
include /etc/nginx/snippets/security-headers.conf;Test and reload
Check the syntax first, then confirm from outside.
sudo nginx -t && sudo systemctl reload nginx curl -sI https://your-domain.com | grep -Ei 'strict-transport|x-content|referrer'
Common mistakes
- A long HSTS value on a site that still has an HTTP-only subdomain.
- Copying a strict CSP from a tutorial and breaking analytics, fonts or the payment form.
- Setting headers in the server block and losing them in a location with its own add_header.
How to undo it
Remove the lines and reload nginx. Browsers remember HSTS for the max-age you sent, so keep it short at first.
Sources
Commands are for Debian and Ubuntu unless noted. Test on a copy first and keep a backup: you are responsible for changes on your own systems.