6

I have simple location used for server-generated caches:

location /api/get-hloc {


#add acccess-allow headers
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';

#try cached files
        root /dev/shm/get-hloc/;
        try_files /$arg_hash.hloc /stocks/graphics/get-iis-graphic?$args;
}

What it does? It simply checks if there is a file in memory, that can be served for request and if there is no file, tries the location that actually generates file for future requests and serves it to the client.

It all works as expected, except add_header directive which is ignored.

Is it possible to addheaders before trying new location in try_files or I should add headers at the endpoint location only?

1 Answer 1

3

Try adding "always" to the add_header directive:

If the always parameter is specified (1.7.5), the header field will be added regardless of the response code.

See documentation for more details.

For your example it would look like this:

location /api/get-hloc {
  #add acccess-allow headers
  add_header 'Access-Control-Allow-Origin' '*' always;
  add_header 'Access-Control-Allow-Credentials' 'true' always;
  add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
  add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type' always;

  #try cached files
  root /dev/shm/get-hloc/;
  try_files /$arg_hash.hloc /stocks/graphics/get-iis-graphic?$args;
}

Keep an eye on following paragraph of the documentation:

There could be several add_header directives. These directives are inherited from the previous level if and only if there are no add_header directives defined on the current level.

This means that if you have add_header directives on a previous level (e.g. server level) they will be ignored and only add_header directives of the current location level(s) will be used.

3
  • Thanks a lot, but the server level headers are needed - is there a way to make wide-open nginx cors config, without permanently deleting all server level headers? Jun 29, 2016 at 10:20
  • repeat them in the location section ;-) Jul 1, 2016 at 18:04
  • what about cookies? they also get removed? I cant repeat them in location level Jul 2, 2016 at 9:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .