How to set a conditional Content-Security-Policy?

Maxim Dounin mdounin at
Tue Mar 27 17:27:05 UTC 2018


On Tue, Mar 27, 2018 at 09:50:14AM -0700, hal469 at wrote:

> For my nginx server, I set a CSP header
>  set $CSP '';
>  set $CSP "${CSP}default-src 'self';";
>  set $CSP "${CSP}script-src  'self';";
>  add_header Content-Security-Policy $CSP;
> For a webapp, using Symfony, the developer UI injects inline script for display of a "Debug Toolbar"
> It's access-blocked by that^ server policy.
> Changing
> -	set $CSP "${CSP}script-src  'self';";
> +	set $CSP "${CSP}script-src  'self' 'unsafe-inline';";
> fixes the problem -- access the debug toolbar is allowed, and it's rendered.
> But, adding the 'unsafe-inline' is certainly not ideal!
> Apache has the option to create/return a CSP policy depending on Request IP:
> How would the equivalent be done in nginx config?
> Iiuc, there's no if/then/else construct.
> Something with maps maybe?

There are "if" constructs in nginx, see
On the other hand, if you want to set CSP depending on the client 
IP address, it might be better idea to use "geo" instead, e.g.:

geo $csp {
    default     "default-src 'self'; script-src 'self';";  "default-src 'self'; script-src 'self' 'unsafe-inline'";

add_header Content-Security-Policy $csp;

See for 

Maxim Dounin

More information about the nginx mailing list