Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make nginx CORS configuration work when server returns error?

Tags:

cors

nginx

I want to add CORS to my server.

I have configured my nginx according to this: https://michielkalkman.com/snippets/nginx-cors-open-configuration.html

It seems to work fine when the server returns 200. However, if the server returns something else, like 400 when the request is wrong, or 500 if internal error, the browser shows the No 'Access-Control-Allow-Origin' header instead of reaching the error handler like it should.

What configuration am I missing to make it work?

like image 991
guy mograbi Avatar asked Jan 26 '15 23:01

guy mograbi


People also ask

How do you fix a CORS issue on a server?

Cross-Origin Resource Sharing (CORS) errors occur when a server doesn't return the HTTP headers required by the CORS standard. To resolve a CORS error from an API Gateway REST API or HTTP API, you must reconfigure the API to meet the CORS standard.

How do I get around CORS error?

Open a network tab in your console. In the response header look for the Access-Control-Allow-Origin header. If it does not exist then add it as a middleware in the way we discussed above. If it does exist then make sure there is no URL mismatch with the website.

Does NGINX support CORS?

To enable CORS on NGINX, you need to use the add_header directive and add it to the appropriate NGINX configuration file. to allow access from any domain.


2 Answers

Since version 1.7.5 you can use the always keyword to return the headers regardless of the response code:

add_header 'Access-Control-Allow-Origin' '*' always;

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

like image 135
Lucas Basquerotto Avatar answered Sep 20 '22 13:09

Lucas Basquerotto


This has been answered before: https://serverfault.com/questions/431274/nginx-services-fails-for-cross-domain-requests-if-the-service-returns-error.

add-header doesn't work with HTTP errors, but the optional headers_more module can be used to workaround this limitation.

like image 33
Ryan Avatar answered Sep 18 '22 13:09

Ryan