Content-Security-Policy: How to Stop XSS Attacks
28/07/2026
Cross-site scripting (XSS) has topped the list of the most common website attacks for years. The attacker injects malicious JavaScript into your page, and the browser runs it as if it were yours — stealing cookies, redirecting users or altering content. Content-Security-Policy (CSP) is the defence that tells the browser exactly which code sources it is allowed to trust.
How CSP works
CSP is an HTTP header with a list of rules (directives). Each directive defines where a given type of resource may be loaded from. For example, script-src ''self'' means: run scripts from my domain only, and block everything else — inline scripts, scripts from other domains. If an attacker manages to inject a script, the browser simply will not run it, because it is not on the allow list.
The most important directives
- default-src — the fallback rule for any resource type not listed separately.
- script-src — where JavaScript may come from; this is where the biggest security win is.
- style-src — where CSS styles may come from.
- img-src — where images may come from.
- frame-ancestors — who may embed you in an iframe; prevents clickjacking.
How to roll it out without breaking your site
The biggest mistake is to enforce a strict policy immediately and then watch half the site stop working — analytics, maps, embedded video. So always start in report-only mode: the Content-Security-Policy-Report-Only header blocks nothing, it only reports what it would block. Run it for a few days, collect the reports, add legitimate sources to the list, and only then switch to the real, enforcing header. On WordPress, be ready to allow the sources your plugins load.
On shared hosting you add CSP through .htaccess or server settings. If you would rather not fiddle, our WordPress hosting plans come with a WAF and easy security-header configuration. Take a look at the plans and raise your protection level without the hassle.
Frequently asked questions
Does CSP replace a WAF? No — CSP protects in the user browser, a WAF protects on the server. They work together, not instead of each other.
Do inline scripts have to go? Ideally yes, or give them a nonce/hash. Inline code is the single biggest source of XSS risk.
CSP is one of several security HTTP headers; be sure to enable HSTS for forced HTTPS, and for broader protection read about WAF website protection.