How to Add a Content-Security-Policy Header
What is this?
A Content-Security-Policy (CSP) header tells browsers which sources of content are trusted on your page. Without it, your site is vulnerable to cross-site scripting (XSS) attacks where malicious scripts can execute in your users' browsers.
Why it matters
- Security: Prevents XSS, the most common web vulnerability
- Compliance: Required by many security standards and audits
- Trust: Shows visitors and partners that you take security seriously
How to fix it
Nginx
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self';" always;
Apache
Add to your .htaccess or virtual host configuration:
Header always set Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self';"
Caddy
header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'"
Node.js / Express
const helmet = require('helmet');
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:"],
}
}));
Cloudflare
- Go to your domain dashboard
- Click Rules > Transform Rules > Modify Response Header
- Add a new rule setting the
Content-Security-Policyheader
Common mistakes
- Starting with a too-strict policy that breaks your site. Use
Content-Security-Policy-Report-Onlyfirst to test without enforcement. - Forgetting to allow inline styles needed by your framework. Many CSS frameworks require
'unsafe-inline'for thestyle-srcdirective. - Not including CDN domains your scripts and fonts load from. Check your browser console for blocked resource errors.
Test your fix
After implementing CSP, audit your site on BeaverCheck to verify the header appears in the Security tab.