Content-Security-Policy
SecurityActiveThe Content-Security-Policy (CSP) header controls which resources a browser is allowed to load for a page. It is the primary defense against Cross-Site Scripting (XSS) attacks by specifying trusted sources for scripts, styles, images, and other resources. A strong CSP prevents injection attacks even if user input reaches the page.
Content-Security-Policy: <directive> <source>[; <directive> <source>]*
Description
CSP uses a whitelist approach – only resources from specified origins are allowed. The default-src directive sets the default policy for all resource types not explicitly listed. script-src controls JavaScript. style-src controls CSS. Violations can be reported to a URI via the report-uri or report-to directives.
Directives
| Directive | Description |
|---|---|
| default-src | Fallback for all resource types not explicitly defined. |
| script-src | Valid sources for JavaScript. Use 'nonce-<value>' or 'sha256-<hash>' for inline scripts. |
| style-src | Valid sources for CSS stylesheets. |
| img-src | Valid sources for images. |
| connect-src | Valid targets for fetch, XMLHttpRequest, WebSocket. |
| frame-ancestors | Controls which origins can embed this page in iframes. Replaces X-Frame-Options. |
| report-uri | URI to receive violation reports (deprecated, use report-to). |
Examples
Strict CSP
http
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-abc123'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:Report-only mode
http
Content-Security-Policy-Report-Only: default-src 'self'; report-uri /csp-violations