34

I'm using Nginx to serve static files in response to CORS requests using the technique outlined in this question. However, when the file doesn't exist the 404 response does not contain the Access-Control-Allow-Origin: * header and so is block by the browser.

How can I send Access-Control-Allow-Origin: * on 404 responses?

0

2 Answers 2

45

Even though this was asked long ago, I was compiling nginx with more module, but with newer version of nginx, I found I don't have to custom compile nginx, all I needed was to add always directive.

http://nginx.org/en/docs/http/ngx_http_headers_module.html

Syntax: add_header name value [always];

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

So a tuned version of CORS headers:

            if ($cors = "trueget") {
                    # Tells the browser this origin may make cross-origin requests
                    # (Here, we echo the requesting origin, which matched the whitelist.)
                    add_header 'Access-Control-Allow-Origin' "$http_origin" always;

                    # Tells the browser it may show the response, when XmlHttpRequest.withCredentials=true.
                    add_header 'Access-Control-Allow-Credentials' 'true' always;
            }
1
  • 3
    always was the key. Thank you for pointing this me out, I was going mad!
    – bgondy
    Jul 22, 2016 at 14:43
13

I'm assuming that you're currently using add_header directive. The documentation notes that this only sets the header for 200, 204, 301, 302 and 304 status code. To set the header for 404 status codes you'll need to use the more_set_headers directive from the headers_more module (you may need to recompile nginx to get this module). The following would set the header for all status codes:

more_set_headers 'Access-Control-Allow-Origin: *';

You can also restrict it to specific status codes:

more_set_headers -s '404' 'Access-Control-Allow-Origin: *';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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