NGINX
Boost Web Security with a Content Security Policy (CSP)
Harden your web application against XSS and data injection by configuring a robust Content Security Policy (CSP) via Nginx, restricting script and resource sources.
server {
listen 80;
server_name yourdomain.com;
# ... other server configurations ...
add_header Content-Security-Policy "
default-src 'self';
script-src 'self' https://trusted-cdn.com;
style-src 'self' 'unsafe-inline';
img-src 'self' data:;
font-src 'self' https://fonts.gstatic.com;
connect-src 'self' ws://yourdomain.com;
frame-src 'self';
object-src 'none';
base-uri 'self';
form-action 'self';
frame-ancestors 'self';
upgrade-insecure-requests;
block-all-mixed-content;
report-uri /csp-report-endpoint;
";
# Optionally add other security headers
add_header X-Frame-Options "DENY";
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
location / {
# ... proxy_pass or root directives ...
}
# Add a location for CSP violation reports (optional)
location /csp-report-endpoint {
default_type application/json;
return 200 '{"status": "ok", "message": "CSP report received"}'; # In a real app, log this report
}
}
How it works: This Nginx configuration snippet demonstrates how to implement a Content Security Policy (CSP) by adding the `Content-Security-Policy` HTTP header. CSP is a powerful security mechanism that helps mitigate Cross-Site Scripting (XSS) and other client-side injection attacks by specifying trusted sources for various content types (scripts, styles, images, etc.). The directives like `script-src 'self'` restrict scripts to only come from your own domain, significantly reducing the attack surface. It also includes other recommended headers like `X-Frame-Options` and `X-Content-Type-Options` for broader protection.