NGINX
Configure a Robust Content Security Policy (CSP)
Learn to implement a strong Content Security Policy (CSP) HTTP header in Nginx to mitigate XSS attacks and control resource loading for enhanced web security.
add_header Content-Security-Policy "default-src 'self';
script-src 'self' 'unsafe-inline' https://cdn.example.com;
style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;
img-src 'self' data: https://images.example.com;
font-src 'self' https://fonts.gstatic.com;
connect-src 'self' wss://socket.example.com;
frame-src 'self' https://player.vimeo.com;
object-src 'none';
base-uri 'self';
form-action 'self';
frame-ancestors 'self';
block-all-mixed-content;
upgrade-insecure-requests;" always;
How it works: This Nginx configuration adds a Content Security Policy (CSP) HTTP header. CSP helps prevent various types of attacks, including Cross-Site Scripting (XSS) and data injection, by whitelisting the sources of content that the browser is allowed to load. 'default-src 'self'' is the fallback for most directives, allowing resources only from the same origin. Specific directives like 'script-src' and 'style-src' explicitly define allowed sources for scripts and stylesheets. 'unsafe-inline' should be used sparingly and carefully, ideally replaced with nonces or hashes. 'block-all-mixed-content' and 'upgrade-insecure-requests' ensure all content is loaded via HTTPS, improving security against passive eavesdropping.