Nginx Content-Security-Policy Header

A Content-Security-Policy tells the browser which sources it may load scripts, styles, images and connections from. It is the strongest defence against cross-site scripting that you can add at the web server.

Start strict

Begin with default-src 'self' and add only the sources the page really needs. Avoid 'unsafe-inline' and 'unsafe-eval'; every exception weakens the policy.

add_header Content-Security-Policy "default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'" always;

Roll out in report-only mode

Send Content-Security-Policy-Report-Only first, review the violations, then switch to the enforcing header.

Open the Content-Security-Policy generator

Frequently asked questions

Does frame-ancestors replace X-Frame-Options?

Yes in modern browsers. Sending both is harmless and covers older clients.

Why is my inline script blocked?

A script-src without 'unsafe-inline' blocks inline code. Move it to a file, or use a nonce or hash.

Guides