Updated April 2026
CSP (Content Security Policy)
Content Security Policy (CSP) is an HTTP response header that tells browsers which resources — scripts, styles, fonts, images — are allowed to load on a page. It is the primary browser-enforced defense against XSS attacks. Resources from unlisted sources are blocked and logged.
What CSP controls
CSP uses directives to specify allowed sources for each resource type:
Content-Security-Policy: default-src 'self'; script-src 'self' https://www.googletagmanager.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' https://fonts.gstatic.com; connect-src 'self' https://www.google-analytics.com; frame-ancestors 'none'; object-src 'none';
Key directives
| Directive | Controls |
|---|---|
default-src | Fallback for all fetch directives not specified |
script-src | JavaScript files and inline scripts |
style-src | CSS files and inline styles |
connect-src | fetch, XHR, WebSocket, EventSource |
frame-ancestors | Which sites can embed this page in an iframe |
object-src | Flash and plugin content — set to none |
Report-Only mode — deploy safely
Always deploy CSP as Content-Security-Policy-Report-Only first. Violations appear in the browser console without blocking anything. Switch to enforcing once violations stop:
# Step 1 — report only, nothing blocked add_header Content-Security-Policy-Report-Only "default-src 'self'" always; # Step 2 — enforce once clean add_header Content-Security-Policy "default-src 'self'" always;
unsafe-inline — when you're stuck
'unsafe-inline' in script-src defeats XSS protection entirely. For styles it's less dangerous. If you have inline scripts you can't remove, use nonces instead:
script-src 'self' 'nonce-RANDOM_PER_REQUEST'Generate a CSP from your live page — CSPFixer →