Dynamic Content Security Policy (CSP) FTW!

So is a small follow up on my other blog post about temporary HPKP which you can read here. This blog post is about how to set a dynamic CSP across your website. This will work with most web servers but I'll be using Nginx.

How and Why?

If you're running a website and you really care about your visitors you should have a CSP because it will protect against several types of client attacks. Also, it can give better privacy by denying content to be loaded cross-origin(information disclosure).

If you have a part of your website that uses Google Captcha, showing some CDN-content, using an (i)frame, a form, inline-style or script and so on you need to whitelist these things in your CSP-rule. But what if the clients only need to get content from Google on, lets say /register/? Well, then you can simply send out a special CSP-rule for that path and different ones on other paths by configure your web server a little bit. This will absolutely reduce the attack surface heavily depending on how your current CSP-rule looks like.

Anyway, in Nginx you can dome something like:

location ~ / {
if ($args ~ mode=register) {
add_header Content-Security-Policy "img-src..."

And this will match if the URL has the mode-parameter with the value "register". Of course you can use this without $args, if you don't need it you remove the if-clause and add the path in the location, like location /reg/ {...}


It could be time consuming to create a CSP for every different path on your website so you should focus on the vital parts first, like login, register, settings and so on.

Then it could look something like:

If you have a few location-directives your web server may be slower, but you can always add the CSP in meta-tags.