What is Content Security Policy?

Content Security Policy (CSP) is an HTTP header that defines which content sources the browser is allowed to load: JavaScript scripts, CSS stylesheets, images, fonts, iframes. It acts as an allowlist: anything not on the list is automatically blocked, even if malicious code manages to be injected into the page.

The attack CSP blocks: XSS

XSS (Cross-Site Scripting) is one of the most common web attacks. It involves injecting malicious JavaScript code into a page viewed by other users — via a form, a comment, or a vulnerability in a CMS (Content Management System, like WordPress or Joomla). This script can then steal session cookies (authentication data stored in the browser), redirect visitors to a fraudulent site, or display fake forms to harvest passwords.

A well-configured CSP blocks the execution of any unauthorised script, even if the injection has succeeded.

Essential CSP directives

  • default-src 'self': by default, only allow resources from the same domain
  • script-src: allowlist of authorised JavaScript sources
  • style-src: authorised CSS sources
  • img-src: authorised image sources
  • frame-src 'none': forbids loading any iframe
  • connect-src: authorised URLs for network calls (fetch, XMLHttpRequest)

CSP example on Apache

Header always set Content-Security-Policy   "default-src 'self';    script-src 'self' https://cdn.example.com;    style-src 'self' 'unsafe-inline';    img-src 'self' data: https:;    frame-src 'none'"

Deploy without breaking your site: Report-Only mode

The Content-Security-Policy-Report-Only directive lets you test a CSP in monitoring mode: violations are reported (in the browser console or to a report URL) without content being blocked. Essential for a gradual rollout without risking service interruption.

Header always set Content-Security-Policy-Report-Only   "default-src 'self'; report-uri /csp-report"

Common pitfalls to avoid

'unsafe-inline' and 'unsafe-eval' in script-src cancel much of CSP's protection. 'unsafe-inline' allows scripts written directly in HTML (<script> tags without an external source), which is exactly the XSS attack vector. Prefer hashes (cryptographic fingerprints of the code: 'sha256-...') or nonces (random single-use tokens: 'nonce-abc123') for legitimate inline scripts.

Check your CSP

TheSiteFuse analyses your CSP, detects missing directives and dangerous values. Audit your site for free to get a detailed report and concrete recommendations.