NGINX
Configure Content Security Policy (CSP) Header in Nginx
Learn to implement a robust Content Security Policy (CSP) in Nginx to mitigate cross-site scripting (XSS) and other content injection attacks on your web application.
server {
listen 80;
server_name your_domain.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
server_name your_domain.com;
# SSL certificate configuration (omitted for brevity)
# ssl_certificate /etc/nginx/ssl/your_domain.crt;
# ssl_certificate_key /etc/nginx/ssl/your_domain.key;
add_header Content-Security-Policy "default-src 'self';
script-src 'self' 'unsafe-inline' 'unsafe-eval' https://trusted-cdn.com;
style-src 'self' 'unsafe-inline';
img-src 'self' data: https://trusted-images.com;
font-src 'self' https://trusted-fonts.com;
connect-src 'self' https://api.your_domain.com;
frame-ancestors 'none';
form-action 'self';";
# ... other server configurations ...
location / {
# Your application's proxy pass or root directive
# proxy_pass http://localhost:3000;
# root /var/www/your_app;
# index index.html;
}
}
How it works: This Nginx configuration snippet demonstrates how to add a Content Security Policy (CSP) header to your web application responses. CSP helps mitigate Cross-Site Scripting (XSS) and data injection attacks by allowing you to define which sources of content (scripts, stylesheets, images, etc.) are permitted to load and execute on your site. The example uses common directives like `default-src`, `script-src`, `style-src`, `img-src`, `font-src`, `connect-src`, `frame-ancestors` (to prevent clickjacking), and `form-action`. Remember to customize the allowed sources (`'self'`, specific domains, `'unsafe-inline'`, `'unsafe-eval'`) based on your application's actual needs to ensure optimal security without breaking functionality.