Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx services fails for cross-domain requests if the service returns error

Tags:

cors

nginx

I am making a cross domain request in my web app.

I have set the CORS headers on Nginx. Everything is working fine except when the service returns an error like 404, 400, 500 etc, instead of receiving the error code, the service is failing with an error saying that the Origin *********** is not allowed by Access-Control-Allow-Origin.

Any ideas why this might be happening?

like image 512
Niyaz Avatar asked Sep 24 '12 05:09

Niyaz


People also ask

How do I enable CORS in nginx?

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.

What is cross origin error?

Cross-Origin Resource Sharing (CORS) is a standard that allows a server to relax the same-origin policy. This is used to explicitly allow some cross-origin requests while rejecting others. For example, if a site offers an embeddable service, it may be necessary to relax certain restrictions.

What is CORS policy no access-control-allow-origin?

The response to the CORS request is missing the required Access-Control-Allow-Origin header, which is used to determine whether or not the resource can be accessed by content operating within the current origin.


2 Answers

Answer found here:

Unfortunately add_header won't work with status codes other than 200, 204, 301, 302 or 304. You can find this in the documentation here.

You may be able to use this plugin to do what you want:

http://wiki.nginx.org/NginxHttpHeadersMoreModule

like image 54
Niyaz Avatar answered Sep 22 '22 02:09

Niyaz


As of v1.7.5 of nginx, you can add "always" to the end of the add_header line to solve this.

like image 44
Thabo Avatar answered Sep 21 '22 02:09

Thabo