NGINX
Implementing a Strict Content Security Policy with Nginx
Configure Nginx to deploy a robust Content Security Policy (CSP) header, dramatically reducing XSS risks by controlling allowed content sources.
server {
listen 80;
listen 443 ssl;
server_name example.com;
# ... other server configurations ...
add_header Content-Security-Policy "default-src 'self';
script-src 'self' https://cdn.example.com;
style-src 'self' https://fonts.googleapis.com;
img-src 'self' data: https://img.example.com;
font-src 'self' https://fonts.gstatic.com;
connect-src 'self' wss://api.example.com;
frame-ancestors 'none';
object-src 'none';
base-uri 'self';
form-action 'self';" always;
# ... more server configurations ...
}
How it works: This Nginx configuration snippet sets a Content Security Policy (CSP) header for `example.com`. CSP is a powerful security mechanism that helps mitigate Cross-Site Scripting (XSS) attacks by defining approved sources of content that the browser is allowed to load. `default-src 'self'` restricts most resources to the same origin. Specific directives like `script-src` and `style-src` allow specifying additional trusted sources (e.g., CDN URLs). The `frame-ancestors 'none'` directive prevents the page from being embedded in iframes, combating clickjacking. This policy significantly hardens your application against various content injection vulnerabilities.