NGINX

Implement Robust Content Security Policy (CSP) via Nginx

Secure your web application against XSS and data injection attacks by implementing a strong Content Security Policy (CSP) header directly in your Nginx configuration.

# In your Nginx server block configuration (e.g., /etc/nginx/sites-available/your_site.conf)

server {
    listen 80;
    server_name yourdomain.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    server_name yourdomain.com;

    # ... other SSL/TLS configurations ...

    # Implement a strict Content Security Policy (CSP)
    # This is an example, adjust directives based on your application's needs
    add_header Content-Security-Policy "
        default-src 'self';
        script-src 'self' https://trusted-cdn.com 'nonce-{random-string}'; # Use nonces for inline scripts
        style-src 'self' https://trusted-cdn.com 'unsafe-inline'; # Consider strict-dynamic/hashes for inline styles
        img-src 'self' data: https://cdn.example.com;
        font-src 'self' https://fonts.gstatic.com;
        connect-src 'self' wss://your-websocket.com;
        frame-src 'self';
        object-src 'none';
        base-uri 'self';
        form-action 'self';
        frame-ancestors 'self';
        upgrade-insecure-requests;
        block-all-mixed-content;
        report-uri https://your-csp-report-endpoint.com/report;
    " always;

    # Optional: Report-Only mode for testing (removes 'always' keyword and adds '-Report-Only')
    # add_header Content-Security-Policy-Report-Only "..." always;

    # ... other server configurations ...
}
How it works: This Nginx configuration snippet demonstrates how to implement a robust Content Security Policy (CSP) as an HTTP header. CSP is a powerful security feature that helps mitigate XSS and other client-side injection attacks by specifying which resources (scripts, styles, images, etc.) the browser is allowed to load and execute. The `add_header` directive injects the policy into all responses. This example includes common directives, showing how to restrict sources, enforce HTTPS, and configure a reporting endpoint for policy violations, offering a strong layer of defense beyond basic security headers.

Need help integrating this into your project?

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

Hire DigitalCodeLabs