Content Security Policy (CSP) is an HTTP header that tells browsers which sources of content are trusted. It dramatically reduces the risk of Cross-Site Scripting (XSS) attacks.
How CSP Works
A CSP header tells the browser: "Only load scripts, styles, and images from these approved sources." If an attacker manages to inject a malicious script, the browser will refuse to execute it because the source isn't in the approved list.
Adding CSP via .htaccess
Add this to your .htaccess to set a basic CSP:
Header set Content-Security-Policy "default-src 'self'; script-src 'self' https://trusted-cdn.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;"Start restrictive and loosen as needed based on browser console errors.
Using Report-Only Mode
Before enforcing CSP, use report-only mode to identify what would be blocked without actually blocking anything:
Header set Content-Security-Policy-Report-Only "default-src 'self';"Check your browser console for CSP violation reports.