Add a Content-Security-Policy on nginx
Why it matters
Without a CSP the browser runs any script that ends up in your pages, so a single injection bug gives an attacker control of what visitors see and do. A policy limits where scripts, frames and plugins may load from.
Staged change. Do this in stages and check each one before the next, so a mistake does not break your site or your mail.
The fix
- Stage 1: save the snippet below and include it in every server block of the site, and in every location block that has add_header lines of its own, because those replace inherited add_header lines (on nginx 1.29.3 and later, add_header_inherit merge; avoids this). Run sudo nginx -t and reload.
- Browse every page type with the developer console open and add the sources it reports to the policy.
- Stage 2: when nothing legitimate is reported, rename the header to Content-Security-Policy and reload. nginx has no nonce feature of its own; the $request_id + sub_filter workaround is fragile (uncompressed upstream, no caching), so let the application send the CSP with a nonce.
/ etc/ nginx/ snippets/ csp.conf
# Stage 1: report only. add_header Content-Security-Policy-Report-Only "default-src 'self'; script-src 'self'; img-src 'self' data: https:; object-src 'none'; base-uri 'self'; frame-ancestors 'self'; form-action 'self'" always; # Optional reporting to a collector you run: uncomment, then append # "; report-to csp" to the policy above. # add_header Reporting-Endpoints 'csp="https://your-collector/csp"' always; # Stage 2: same value, header renamed to Content-Security-Policy.
Related
- Reported by the Content-Security-Policy check
- Enforce the report-only Content-Security-Policy
- Send the Content-Security-Policy as an HTTP header
- Restrict where scripts can load from
- Replace 'unsafe-inline' scripts with nonces or hashes
- Remove 'unsafe-eval' from script-src
- Remove wildcard sources from script-src
- Set object-src to 'none'
- Add base-uri to the Content-Security-Policy
- Reduce reliance on inline styles
- Fix the Content-Security-Policy syntax
Scan your domain to see whether this applies to you.