1

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;
  ...
}
3

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.

  • Now why didn't I think of that?! This is a neat approach, thank you! – eternaltyro May 23 at 8:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.