NGINX

Configuring a Robust Content Security Policy (CSP) Header in Nginx

Implement a strong Content Security Policy (CSP) in Nginx to mitigate XSS and data injection attacks by restricting resource loading origins and trusted execution sources.

server {
    listen 80;
    server_name example.com www.example.com;

    # Redirect HTTP to HTTPS (recommended for production)
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name example.com www.example.com;

    ssl_certificate /etc/nginx/ssl/example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com.key;

    # Content Security Policy (CSP) Header
    # Restricts sources for various content types
    add_header Content-Security-Policy "
        default-src 'self' https://trusted.cdn.com;
        script-src 'self' 'unsafe-inline' 'unsafe-eval' https://ajax.googleapis.com;
        style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;
        img-src 'self' data: https://img.example.com;
        font-src 'self' https://fonts.gstatic.com;
        connect-src 'self' https://api.example.com;
        frame-src 'self' https://www.youtube.com;
        object-src 'none';
        base-uri 'self';
        form-action 'self';
        frame-ancestors 'self';
        upgrade-insecure-requests;
        block-all-mixed-content;
        report-uri https://csp-reporting.example.com/report;
    " always;

    # Other security headers (for completeness, but focus is CSP)
    add_header X-Frame-Options "DENY" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "no-referrer-when-downgrade" always;

    location / {
        proxy_pass http://localhost:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
How it works: This Nginx configuration snippet demonstrates how to implement a robust Content Security Policy (CSP) header, a powerful security mechanism to prevent a wide range of attacks, including Cross-Site Scripting (XSS) and data injection. CSP works by defining trusted sources for various types of content (scripts, styles, images, etc.) that a web browser is allowed to load and execute. Directives like `script-src` and `style-src` specify allowed origins, preventing the execution of unauthorized scripts or styles. The `report-uri` directive can optionally be used to send violation reports, helping to fine-tune the policy. This layered defense significantly reduces the attack surface of web applications.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs