← Back to all snippets
NGINX

Enforce Content Security Policy (CSP) via Nginx Headers

Implement a robust Content Security Policy (CSP) using Nginx server configuration to mitigate XSS and data injection attacks by restricting resource loading.

# In your Nginx server block (e.g., /etc/nginx/sites-available/your-site.conf)
server {
    listen 80;
    server_name example.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name example.com;

    # ... other SSL/server configurations ...

    # Content Security Policy (CSP) Header
    add_header Content-Security-Policy "default-src 'self';\
                                          script-src 'self' https://trusted-cdn.com;\
                                          style-src 'self' 'unsafe-inline' https://trusted-cdn.com;\
                                          img-src 'self' data: https://trusted-images.com;\
                                          font-src 'self' https://fonts.gstatic.com;\
                                          object-src 'none';\
                                          base-uri 'self';\
                                          form-action 'self';\
                                          frame-ancestors 'none';\
                                          report-uri /csp-report-endpoint;";

    root /var/www/your-site;
    index index.html index.php;

    location / {
        try_files $uri $uri/ =404;
    }

    # ... other location blocks ...
}
How it works: This Nginx configuration snippet demonstrates how to implement a Content Security Policy (CSP) using an HTTP header. CSP is a powerful security mechanism that helps mitigate various attacks, especially XSS, by defining which resources (scripts, styles, images, etc.) the browser is allowed to load and execute. By configuring it via Nginx, you ensure the policy is applied to all served content. The example policy restricts most resources to 'self' (same origin) but allows specific trusted origins for scripts, styles, and images, and disables certain potentially unsafe features like `object-src` and `frame-ancestors`. A `report-uri` is included for monitoring policy violations.

Need help integrating this into your project?

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

Hire DigitalCodeLabs