← Back to all snippets
NGINX

Implement a Content Security Policy (CSP) Header

Enhance web security by implementing a strong Content Security Policy (CSP) header in Nginx to mitigate XSS, data injection, and other client-side attacks.

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

    # Redirect HTTP to HTTPS
    return 301 https://$host$request_uri;
}

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

    # SSL certificate configuration
    # ...

    # Content Security Policy (CSP) header
    # This CSP allows scripts and styles only from the same origin,
    # images from any origin, fonts from Google Fonts,
    # and disallows object/embed tags.
    add_header Content-Security-Policy "default-src 'self';
          script-src 'self' https://trusted.cdn.com;
          style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;
          img-src 'self' data: https:;
          font-src 'self' https://fonts.gstatic.com;
          object-src 'none';
          base-uri 'self';
          form-action 'self';
          frame-ancestors 'self';";

    # Other security headers (optional but recommended)
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";
    add_header X-XSS-Protection "1; mode=block";
    add_header Referrer-Policy "no-referrer-when-downgrade";

    root /var/www/html;
    index index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }
}
How it works: This Nginx configuration snippet demonstrates how to set a robust Content Security Policy (CSP) header. CSP is a powerful security mechanism that helps mitigate Cross-Site Scripting (XSS) and other client-side injection attacks by specifying allowed sources for content like scripts, stylesheets, images, and fonts. By defining strict rules (`'self'`, specific URLs, `'none'`, etc.), you can prevent browsers from loading or executing malicious resources from unauthorized domains, significantly enhancing your web application's security posture.

Need help integrating this into your project?

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

Hire DigitalCodeLabs