nginx try_files addheader doesnt work

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?


Solution 1:

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.