NGINX
Implementing a Strong Content Security Policy (CSP) Header in Nginx
Harden your web application's security by configuring a robust Content Security Policy (CSP) header in Nginx to mitigate XSS and data injection attacks.
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name example.com www.example.com;
# SSL certificate configuration (omitted for brevity)
# ssl_certificate /etc/nginx/ssl/example.com.crt;
# ssl_certificate_key /etc/nginx/ssl/example.com.key;
# ... other SSL settings ...
# --- Content Security Policy (CSP) Header ---
add_header Content-Security-Policy "
default-src 'self';
script-src 'self' https://trusted.cdn.com 'unsafe-inline';
style-src 'self' https://trusted.cdn.com 'unsafe-inline';
img-src 'self' data: https://cdn.example.com;
font-src 'self' https://fonts.gstatic.com;
connect-src 'self' https://api.example.com;
frame-src 'self';
object-src 'none';
base-uri 'self';
form-action 'self';
frame-ancestors 'self';
report-uri https://report-to-csp-endpoint.com/report;
" always;
# ... other Nginx configurations ...
location / {
# Your application's root configuration
}
}
How it works: This Nginx configuration snippet demonstrates how to implement a robust Content Security Policy (CSP) header. CSP is a powerful security mechanism that helps mitigate Cross-Site Scripting (XSS) and data injection attacks by specifying which sources of content (scripts, styles, images, etc.) are permitted to load or execute on your web page. Each directive (e.g., `script-src`, `style-src`) defines allowed origins. `'self'` permits resources from the same origin, `https://trusted.cdn.com` allows a specific CDN, `'unsafe-inline'` should be used sparingly as it allows inline scripts/styles. `report-uri` can be used to send violation reports, aiding in policy refinement and attack detection.