NGINX

Implement Content Security Policy (CSP) via Nginx

Enhance your website's security against XSS and data injection by configuring a robust Content Security Policy (CSP) using Nginx server headers.

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

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

    # ... other configurations ...

    add_header Content-Security-Policy "
            default-src 'self';
            script-src 'self' https://trusted.cdn.com 'unsafe-inline' 'unsafe-eval';
            style-src 'self' https://trusted.cdn.com 'unsafe-inline';
            img-src 'self' data: https://trusted.cdn.com;
            font-src 'self' data: https://trusted.cdn.com;
            connect-src 'self' https://api.yourdomain.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://yourdomain.com/csp-report-endpoint;
        " always;

    # ... more configurations ...
}
How it works: This Nginx configuration snippet sets a Content Security Policy (CSP) header for your web application. CSP is a powerful security mechanism that helps mitigate Cross-Site Scripting (XSS) and other code injection attacks by specifying which sources of content (scripts, stylesheets, images, etc.) are allowed to be loaded by the browser. The example provides a strict policy, allowing content only from the same origin ('self') or explicitly trusted domains, while also including directives like `upgrade-insecure-requests` for HTTPS and `report-uri` for monitoring violations.

Need help integrating this into your project?

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

Hire DigitalCodeLabs