Content-Security-Policy
HTTP response header to your Nginx site.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';
Content-Security-Policy
in nginxYou 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;
While it is certainly easy to add a CSP header with nginx, 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
from your application code instead of from nginx.
When you set the header from nginx, the big advantage is that it will can 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 policy for the entire site.
The choice is yours, there is no wrong way to do it, as long as the Content-Security-Policy
response header shows up in the response it will work.
In the above example we are simply setting a policy:
default-src 'self';
Chances are you will need something more complicated than that, so check out the Content Security Policy reference, or take a look at more CSP examples for more info.
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 CopyAdvisory Week is a weekly roundup of all the security advisories published by the major software vendors.