Using Nginx variables in place of CSP values

eternaltyro asked:

I have a fairly long Content-Security-Policy header value and I am having to place it in several location blocks.

Is it possible to declare a variable in the configuration that has the value of my long CSP string and then use the variable in place of the string throughout my location blocks?

Something like this:

location / {
  ...
  set_header Content-Security-Policy $csp_string;
  ...
}
...
location /somethingelse {
  ...
  set_header Content-Security-Policy $csp_string;
  ...
}

My answer:


It’s probably not a great idea to try to use a variable for this, unless you actually want it to be different in different locations.

The best solution for things that have to be repeated is the include. For example I have things like this in my nginx configuration:

        include includes/csp_strict;

Where /etc/nginx/includes/csp_strict contains only:

add_header Content-Security-Policy "default-src 'none'; img-src 'self'; script-src 'self'; style-src 'self'; frame-ancestors 'self'; base-uri 'self'; form-action 'self'";

Another one is includes/csp_wordpress which looks like:

add_header Content-Security-Policy "default-src 'self' 'unsafe-inline'; frame-ancestors 'self'; base-uri 'self';";

I can then include either of these (or many possible others) wherever they are needed.


View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.