NGINX

Implement Content Security Policy (CSP) for XSS Protection in Nginx

Configure a robust Content Security Policy (CSP) in Nginx to mitigate Cross-Site Scripting (XSS) attacks by strictly controlling which resources a user agent can load.

# In your server or http block
add_header Content-Security-Policy "default-src 'self';
    script-src 'self' https://trusted.cdn.com;
    style-src 'self' 'unsafe-inline';
    img-src 'self' data: https://cdn.example.com;
    font-src 'self' https://fonts.gstatic.com;
    connect-src 'self' wss://your-api.com;
    object-src 'none';
    frame-ancestors 'self';
    form-action 'self';" always;

# For reporting violations (optional, replace with your actual reporting endpoint)
# add_header Content-Security-Policy-Report-Only "default-src 'self'; report-uri /csp-report-endpoint;" always;
How it works: This Nginx configuration snippet adds a `Content-Security-Policy` header to all outgoing responses. CSP is a powerful security mechanism that helps mitigate Cross-Site Scripting (XSS) attacks by allowing web administrators to control resources the user agent is allowed to load. Directives like `script-src`, `style-src`, and `img-src` define trusted sources for different resource types, blocking unauthorized content and improving overall application security.

Need help integrating this into your project?

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

Hire DigitalCodeLabs