What is a content security policy?

A content security policy, usually shortened to CSP, is a list of places your pages are allowed to load scripts, styles, images and fonts from. If an attacker manages to inject a script from elsewhere, the browser refuses to run it. It is the most effective defence against cross-site scripting and also the most involved header to set up, so it is the one most sites lack.

Why it matters

Cross-site scripting is the most common way sites are compromised: a comment, a form field or a vulnerable plugin lets someone slip a script into your page, and that script can steal logins, redirect visitors or insert adverts. Every other defence tries to stop the script getting in. A CSP assumes it might and stops it running. For a site that takes card details or holds customer data, it is close to essential.

Why it takes care

The policy must list every legitimate source: your own domain, your analytics provider, your font service, an embedded map, a chat widget. Anything not listed is blocked, so a policy written carelessly breaks the site. That is why it should be introduced in stages.

How to check

Our check looks for the Content-Security-Policy header on your home page. Browsers report anything a policy blocks in the developer console, which is how you find out what still needs listing.

How to fix it

  • Start in report-only mode using the Content-Security-Policy-Report-Only header, which logs what would be blocked without blocking it.
  • Browse the whole site, including forms and logged-in areas, and add each legitimate source the browser reports.
  • Switch the header to Content-Security-Policy once nothing legitimate is reported.
  • Avoid "unsafe-inline" for scripts if you possibly can; it undoes most of the protection.

This is usually a job for a developer, but a simple policy for a brochure site can be written in an hour.

Not sure how your own site does on this? Run the free check: it takes about twenty seconds and reports on this and thirty other things.

Check my website

More guides