webzod
account

Replace 'unsafe-inline' scripts with nonces or hashes on nginx

headers.csp.script_unsafe_inline · effort: a project

Why it matters

With 'unsafe-inline' any script an attacker manages to inject into the page runs, which cancels most of what a CSP protects. Nonces or hashes let only the inline scripts you wrote run.

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

  1. 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. nginx passes the header through.
  2. For static pages, use hashes of the inline scripts in a report-only header first, then enforce.
nginx
# Stage 1 for static pages: one hash per inline script.
add_header Content-Security-Policy-Report-Only "script-src 'self' 'sha256-HASH_OF_INLINE_SCRIPT'; object-src 'none'; base-uri 'none'" always;

Read the documentation (opens in a new tab)

Scan your domain to see whether this applies to you.