Complete Security Guide to Content Security Policy (CSP), HTTP Headers and XSS Mitigation
Content Security Policy (CSP) is one of the most effective browser-enforced security mechanisms for modern web applications. By specifying trusted source domains for scripts, styles, images, and fonts, CSP neutralizes Cross-Site Scripting (XSS), data injection, and malicious iframe embedding (clickjacking).
This generator structures compliant W3C Level 2 & Level 3 CSP directives ready for deployment in Nginx server blocks, Apache .htaccess files, PHP response headers, or HTML <meta> tags.
Anatomy of Key CSP Directives
Configure precise resource boundaries across critical directives:
- default-src: The global fallback origin applied when specific resource directives are omitted.
- script-src: Defines authorized JavaScript origins, protecting application state against injected third-party payloads.
- style-src & font-src: Permits trusted typography and CSS CDNs (such as Google Fonts or Cloudflare CDNJS).
- img-src: Governs image loading, inline SVG schemas, and
data:URIs.
Server Headers (Nginx) vs HTML <meta> Implementation
Delivering CSP via HTTP response headers directly from your Nginx or Apache web server provides optimal protection across the entire document lifecycle. When server header access is constrained, HTML <meta http-equiv="Content-Security-Policy"> tags provide client-level security for static single-page apps.
Eliminating 'unsafe-inline' with Nonces and Hashes
While temporary prototyping frequently uses 'unsafe-inline', production security hardening replaces inline permissions with cryptographic nonces (random one-time tokens generated per HTTP request) or SHA-256 script integrity hashes.
Practical Example
Default: 'self' | Scripts: 'self' cdnjs.cloudflare.com | Styles: 'self' fonts.googleapis.com | Fonts: fonts.gstatic.com
default-src 'self'; script-src 'self' https://cdnjs.cloudflare.com; style-src 'self' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com;
Restricts all assets to same-origin while whitelisting designated typography and JavaScript CDNs.
add_header Content-Security-Policy directive in /etc/nginx/sites-available/
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self';" always;
Injects the policy header into all HTTP 200/300 responses automatically at the web server level.