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;
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With