Skip to main content

Content-Security-Policy

SecurityActive

The 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

DirectiveDescription
default-srcFallback for all resource types not explicitly defined.
script-srcValid sources for JavaScript. Use 'nonce-<value>' or 'sha256-<hash>' for inline scripts.
style-srcValid sources for CSS stylesheets.
img-srcValid sources for images.
connect-srcValid targets for fetch, XMLHttpRequest, WebSocket.
frame-ancestorsControls which origins can embed this page in iframes. Replaces X-Frame-Options.
report-uriURI 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

Related

Specification

W3C RecommendationContent-Security-Policy specification →