NGINX security headers and a Content-Security-Policy that does not break your site
In this article8 sections
Security headers are instructions your server sends with every page, telling the browser how careful to be. A handful of lines can stop a whole class of attacks: pages being framed inside another site, scripts running from places you never approved, browsers guessing file types, connections quietly downgraded to plain HTTP.
They are also easy to get wrong. A policy that is too strict breaks your site on the day you ship it, and an NGINX quirk can make a header vanish from the pages where you thought you had set it. This guide covers what to send, how to send it reliably, and how to introduce the powerful one, Content-Security-Policy, without taking the site down.
The headers worth having
Strict-Transport-Security (HSTS). Tells the browser to use HTTPS only for your domain, for a set time. It protects visitors who type http:// or follow an old link. Start small, because a mistake is remembered by browsers for the whole period:
add_header Strict-Transport-Security "max-age=300" always;
Once every page and every subdomain you care about works over HTTPS, raise it in steps: a day (86400), a week, then six months (15768000) or a year (31536000). Only add includeSubDomains if every subdomain, including forgotten ones, serves HTTPS. Only consider preload if you understand it is a long, hard-to-reverse commitment.
X-Content-Type-Options. Stops browsers guessing a file’s type, which blocks a trick where an uploaded file is run as a script:
add_header X-Content-Type-Options "nosniff" always;
Referrer-Policy. Controls how much of your address is sent to other sites when someone follows a link. A sensible default:
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
Permissions-Policy. Switches off browser features your site does not use, so that a compromised script cannot use them either:
add_header Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=()" always;
Adjust the list: if your site really uses geolocation or payments, leave that one out.
Clickjacking protection. Prevents other sites from putting yours in a frame. The modern way is the frame-ancestors part of the Content-Security-Policy below. The old header still helps older browsers:
add_header X-Frame-Options "SAMEORIGIN" always;
Use DENY if nothing, including your own site, needs to frame your pages.
The add_header trap
This is the detail that makes headers disappear, and it catches experienced people.
In NGINX, add_header lines are inherited from the outer level only if the inner level has none of its own. The moment a location block contains a single add_header (for example a Cache-Control for static files), it stops inheriting the headers set in the server block. Your security headers are gone from exactly those responses, and nothing warns you.
The fix is to put the headers in one file and include that file wherever you set any header:
sudo nano /etc/nginx/snippets/security-headers.conf
add_header Strict-Transport-Security "max-age=300" 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=(), payment=()" always;
add_header X-Frame-Options "SAMEORIGIN" always;
Then include it at the server level, and again inside every location that adds its own header:
server {
listen 443 ssl;
server_name example.com;
include snippets/security-headers.conf;
location ~* \.(css|js|png|jpg|svg|woff2)$ {
include snippets/security-headers.conf;
add_header Cache-Control "public, max-age=2592000";
}
}
Two more details. The word always makes NGINX send the header on error pages too (404, 500), not only on successful responses. And if the application behind NGINX (WordPress, Laravel, a Node app) sends the same header, you will get it twice; decide where each header lives and remove the duplicate.
Check what you actually send
Do not trust the configuration. Look at the response:
curl -sI https://example.com/ | grep -iE 'strict-transport|x-content-type|referrer|permissions|x-frame|content-security'
curl -sI https://example.com/styles.css | grep -iE 'strict-transport|x-content-type'
curl -sI https://example.com/this-page-does-not-exist | head -1
Check an HTML page, a static file and a 404. If a header is missing from one of the three, you have found the inheritance trap. Test the configuration before reloading:
sudo nginx -t && sudo systemctl reload nginx
Content-Security-Policy: the powerful one
A Content-Security-Policy (CSP) is an allow-list: it tells the browser which sources of scripts, styles, images, fonts and connections are legitimate for your pages. If an attacker manages to inject a script tag, a good policy makes the browser refuse to run it. That is why it is the most valuable header, and why it is also the one that breaks sites.
A starting point for a mostly static site:
default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'
Read it as: by default only load things from my own domain; images may also be data: URLs; nobody may frame this page except me.
What breaks it on real sites:
- Inline scripts and styles.
<script>…</script>in the page andstyle="..."attributes are blocked unless you allow them. The right fix is to move scripts to files.'unsafe-inline'for scripts removes most of the protection, so treat it as a last resort and a known gap, not a solution. - Third-party services. Analytics, chat widgets, payment forms, embedded videos, fonts from a font service, captcha. Each needs its own domain added to the right directive.
- Browser extensions. They inject their own code and generate noise in your reports. You will see violations with no source file that are not your site’s fault.
Roll it out in report-only mode
Never start by enforcing. Send the policy as Content-Security-Policy-Report-Only first. The browser then logs what it would have blocked, without blocking anything:
add_header Content-Security-Policy-Report-Only "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'" always;
Open your site with the browser developer tools console open. Every violation is printed with the directive and the blocked address. Click through the pages that matter: home, a form, checkout, login, the admin area. For each message decide: is this legitimate? Then add it to the right directive, or remove the dependency.
For real visitors, add a reporting address. The simplest, widely supported form is the report-uri directive pointing at a small endpoint you control (or a reporting service):
... ; report-uri https://example.com/csp-report
Collect the reports for a few days of normal use. Look for repeated sources (legitimate: add them), and one-off oddities with no source (usually a browser extension: ignore them). When the reports are quiet, rename the header to Content-Security-Policy and reload. Keep the report address, so that a later regression shows up in your logs instead of in a customer complaint.
Admin areas are different
Admin screens often need inline scripts and styles because the software was built that way. It is common and reasonable to use a looser policy for the admin path only, and to protect that path in other ways (a firewall rule, a country restriction, a second factor). Keep the public pages strict, and give the admin paths their own location block with their own header include. Remember the inheritance trap from above.
A short rollout checklist
- Put all headers in one snippet file; include it everywhere a header is set.
- Start HSTS at
300seconds and raise it over weeks. - Check HTML, static files and a 404 with
curl -sI. - Introduce CSP as report-only; fix inline scripts; add each legitimate third party deliberately.
- Enforce when reports are quiet; keep reporting on.
- Re-test after every change to the site’s scripts, fonts or embeds.
When it is worth getting help
The headers are quick. The careful part is the CSP: finding every legitimate script, replacing inline code, and proving that checkout, login and the admin area still work. If your site has payments, a booking form or a lot of third-party scripts, a staged rollout is worth doing carefully once.
I set up and test exactly this on NGINX, including report-only rollouts and enforcement. You can see my profile on Upwork, or read about server hardening. If you also want a Cloudflare layer that does not hide your server from a direct hit, read lock your origin to Cloudflare.