Question: how-to enable CORS
See original GitHub issueHi there,
First of all, thanks for the wonderful package: it simplifies life tremendously!
The issue I’m looking to solve
I’m looking for a way to extend the proxy to enable CORS between subdomains.
More specifically, in a scenario with three services…
jwilder/nginx-proxy
image/foo
withVIRTUAL_HOST=foo.mydomain.com
image/bar
withVIRTUAL_HOST=bar.mydomain.com
… I’d like nginx to set the headers to allow CORS between foo.mydomain.com
and bar.mydomain.com
, but not from outside of the domain (e.g. www.otherdomain.com
).
What the docker-compose file looks like
version: "3.2"
services:
proxy:
image: jwilder/nginx-proxy
ports:
- "80:80"
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
foo:
image: image/foo
env:
- VIRTUAL_HOST=foo.mydomain.com
bar:
image: image/bar
env:
- VIRTUAL_HOST=bar.mydomain.com
What I’ve already tried
I understand that I can replace the default proxy settings, but ideally, I’d just like to extend it with this functionality. Through some googling, I’ve found a way to approach this issue, but I’m unsure about how I’d go about and actually implement this.
The general approach would be to add this block of code in each server
block of /etc/nginx/conf.d/default.conf
:
server {
set $cors "";
if ($http_origin ~* (.*\.mydomain.com)) {
set $cors "true";
}
location / {
if ($cors = "true") {
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, DELETE, PUT';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Headers' 'User-Agent,Keep-Alive,Content-Type';
}
if ($request_method = OPTIONS) {
return 204;
}
}
}
However, this approach overwrites all the other elements in the server
block, such as server_name
, and hence, doesn’t achieve my purposes.
Is there any canonical approach to this problem?
Thanks in advance for your help and insights.
Issue Analytics
- State:
- Created 6 years ago
- Reactions:11
- Comments:18
It would be awesome to have a
ALLOW_CORS
env for this. I was able to enable CORs by editing the vhosts for my specific domain. Below is an example of how to do this.example.com
and attach it to:/etc/nginx/vhost.d/example.com
with contents:This file will only work for example.com, which matches my VIRTUAL_HOST environment variable. I guess you can’t wild card a vhost, so you’ll need to do the same thing for all subdomains if needed. That’s it, it seems to work too. 🎉
Here is my workaround. I’m using
location default configuration
https://github.com/jwilder/nginx-proxy#per-virtual_host-location-default-configuration./etc/nginx/vhost.d/default_location
This will enable CORS for all virtual hosts. Also you can add this code to some of them (check docs)