A scanner flagged missing security headers on my site. Which ones matter, what are safe values, and what can break the site if I set them wrongly?
DEV3 Developer Forum
Which security headers should I add in Nginx, and how do I add HSTS and CSP safely?
Every post is reviewed first. Usually reviewed within 24 hours.
1 reply
Add these in the server block for HTTPS (use always so they apply to error pages too).
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" 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;
What each does
- HSTS forces HTTPS in browsers for the stated time. Start with a short
max-age(for example 300), confirm every subdomain works over HTTPS, then raise it.includeSubDomainsaffects all subdomains;preloadis a near-permanent commitment, so leave it out unless you are certain. - X-Content-Type-Options: nosniff stops MIME sniffing.
- X-Frame-Options /
frame-ancestors: protects against clickjacking. The modern way is the CSP directiveframe-ancestors 'self'. - Referrer-Policy limits URL leaks to other sites.
- Permissions-Policy disables unused browser features.
Content-Security-Policy is the strongest and the easiest to break. Roll it out in report-only mode first:
add_header Content-Security-Policy-Report-Only "default-src 'self'; script-src 'self'; img-src 'self' data: https:; style-src 'self' 'unsafe-inline'; frame-ancestors 'self'" always;
Watch the browser console for violations, add the sources you really use (analytics, fonts, payment widgets), then switch to the enforcing Content-Security-Policy header. Avoid 'unsafe-inline' for scripts; use nonces or hashes if you can.
Pitfall: Nginx add_header in a location replaces the headers inherited from the server level. If a location defines any add_header, repeat all of them there (or use the include file approach).
Check the result with curl -I https://example.com. A generator for starting values is the CSP and security headers generator.