Content Security Policy (CSP)

nginx Content-Security-Policy Headers

Here's how to add a Content-Security-Policy HTTP response header to your Nginx site.

CSP nginx Header Example

Inside your nginx server {} block add:

add_header Content-Security-Policy "default-src 'self';";

Let's break it down, first we are using the nginx directive or instruction: add_header. Next we specify the header name we would like to set, in our case it is Content-Security-Policy. Finally we tell it the value of the header: "default-src 'self';" (you'll probably need to change this value). And don't forget that all nginx configuration directives need to end with a semicolon.

If all is working properly we should now see the following HTTP response header when we make a HTTP request to our nginx server:

Content-Security-Policy: default-src 'self';

Always adding Content-Security-Policy in nginx

You can also append always to the end to ensure that nginx sends the header regardless of response code. The nginx config would look like this:

add_header Content-Security-Policy "default-src 'self';" always;

Should I add a CSP header with nginx or my in application?

While it is certainly easy to add a CSP header with nginx using add_header, it also possible to add a Content-Security-Policy header with your server side programming language (PHP, ExpressJS, etc.). There are tradeoffs to doing it either way. If you have sections of your application that may require a different CSP policy then it might be easier to use your application programming language instead. Or if you plan to use features such as a CSP nonce, then it is much easier to set the Content-Security-Policy header from your application code instead of from nginx.

When you set the CSP header from nginx, the big advantage is that it will be added to all HTTP responses (even your static assets). It is also perhaps simpler to use nginx to add the CSP header if you have one simple content security policy for the entire site.

The choice is yours, there is no wrong way to do it, as long as the Content-Security-Policy header shows up in the HTTP response it will protect your web application.

Dig deeper with CSP

In the above example we are simply setting a CSP policy:

default-src 'self';

Chances are you will need a CSP policy more complicated than that, so check out the Content Security Policy reference, or take a look at more CSP examples for more info.

CSP Developer Field Guide

CSP Developer Field Guide

Want to learn the ins and outs CSP? Grab a copy of the CSP Developer Field Guide. It's a short and sweet guide to help developers get up to speed quickly.

Grab a Copy

Struggling to stay on top of security advisories?

Advisory Week is a weekly roundup of all the security advisories published by the major software vendors.