NGINX
Implement Strict Content Security Policy (CSP)
Configure a robust Content Security Policy (CSP) in Nginx to significantly mitigate Cross-Site Scripting (XSS) and data injection attacks by controlling resource loading.
# Place this inside your server {} block or http {} block in nginx.conf
add_header Content-Security-Policy "
default-src 'self';
script-src 'self' https://trusted-cdn.com;
style-src 'self' 'unsafe-inline'; # Consider moving inline styles to files for stricter CSP
img-src 'self' data: https://cdn.example.com;
font-src 'self' https://fonts.gstatic.com;
connect-src 'self' wss://your-websocket-api.com;
frame-src 'self';
object-src 'none';
base-uri 'self';
form-action 'self';
upgrade-insecure-requests; # Automatically rewrite HTTP requests to HTTPS
block-all-mixed-content; # Block loading of any HTTP assets on an HTTPS page
report-uri /csp-report-endpoint; # Optional: Endpoint to send CSP violation reports
" always;
# Example for handling CSP reports (optional)
# location /csp-report-endpoint {
# proxy_pass http://localhost:8000/csp-reports; # Or directly log it
# proxy_pass_request_body on;
# proxy_set_header Content-Type "application/json";
# }
How it works: This Nginx configuration snippet demonstrates how to implement a comprehensive Content Security Policy (CSP). CSP is an HTTP response header that allows web application administrators to control resources (scripts, stylesheets, images, etc.) that the user agent is allowed to load for a given page. By defining trusted sources for various resource types, this policy acts as a powerful defense against Cross-Site Scripting (XSS) and other client-side injection attacks, significantly enhancing the security posture of the web application.