Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly setup nginx Access-Control-Allow-Origin into response header based on the Origin header from the request?

Tags:

cors

nginx

I am looking for a nginx config setup that does setup the Access-Control-Allow-Origin to the value received in the Origin.

It seems that the * method doesn't work with Chrome and the multiple URLs doesn't work with Firefox as it is not allowed by CORS specification.

So far, the only solution is to setup the Access-Control-Allow-Origin to the value received in the origin (yes some validation could be implemented).

The question is how to do this in nginx, preferably without installing additional extensions.

set $allow_origin "https://example.com" # instead I want to get the value from Origin request header add_header 'Access-Control-Allow-Origin' $allow_origin; 
like image 491
sorin Avatar asked Jan 24 '13 10:01

sorin


People also ask

Does NGINX change Origin header?

NGINX will not replace headers; it will append to them. If you don't hide it first, you'll wind up with 2 origins and this will cause another CORS error.

How do I fix CORS header Access-Control allow Origin missing?

If the server is under your control, add the origin of the requesting site to the set of domains permitted access by adding it to the Access-Control-Allow-Origin header's value. You can also configure a site to allow any site to access it by using the * wildcard. You should only use this for public APIs.


1 Answers

Using if can sometimes break other config such as try_files. You can end up with unexpected 404s.

Use map instead

map $http_origin $cors_header {     default "";     "~^https?://[^/]+\.example\.com(:[0-9]+)?$" "$http_origin"; }  server {     ...     location / {         add_header Access-Control-Allow-Origin $cors_header;         try_files $uri $uri/ /index.php;     }     ...  } 

If is evil

like image 141
phylae Avatar answered Sep 23 '22 04:09

phylae