Nginx CSP Integration
Add CSP headers to your Nginx configuration.
Prerequisites
Section titled “Prerequisites”- Nginx 1.7.5+ (for
add_headersupport) - Access to nginx.conf or site configuration
Quick Start
Section titled “Quick Start”Add to your server or location block:
# Report-only mode (recommended to start)add_header Content-Security-Policy-Report-Only "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; report-uri https://ingest.headerhawk.com/csp/YOUR_SITE_ID" always;Reload Nginx:
sudo nginx -t && sudo nginx -s reloadEnforcement Mode
Section titled “Enforcement Mode”Once you’ve tuned your policy using the reports, switch to enforcement:
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; report-uri https://ingest.headerhawk.com/csp/YOUR_SITE_ID" always;Complete Example
Section titled “Complete Example”server { listen 443 ssl http2; server_name example.com;
# CSP Header add_header Content-Security-Policy-Report-Only " default-src 'self'; script-src 'self' https://cdn.example.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; connect-src 'self' https://api.example.com; report-uri https://ingest.headerhawk.com/csp/YOUR_SITE_ID " always;
# Other security headers add_header X-Content-Type-Options nosniff always; add_header X-Frame-Options DENY always;
location / { # Your config... }}Configuration Tips
Section titled “Configuration Tips”The always Parameter
Section titled “The always Parameter”Include always to send headers for all response codes (including errors):
add_header Content-Security-Policy "..." always;Multiline Policies
Section titled “Multiline Policies”For readability, use multiline strings:
add_header Content-Security-Policy " default-src 'self'; script-src 'self';" always;Per-Location Policies
Section titled “Per-Location Policies”Different policies for different paths:
location /admin { add_header Content-Security-Policy "default-src 'self'; script-src 'self'" always;}
location /public { add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'" always;}Troubleshooting
Section titled “Troubleshooting”Headers Not Appearing
Section titled “Headers Not Appearing”- Check Nginx config:
sudo nginx -t - Verify the
alwaysparameter is included - Check if a proxy is stripping headers
Duplicate Headers
Section titled “Duplicate Headers”If you see duplicate CSP headers, check parent blocks. You may need to consolidate headers in one location.
Verification
Section titled “Verification”Test your configuration:
curl -I https://your-site.com | grep -i content-security-policy