[Tutorial Nginx] Enabling CORS for multiple Domains

hi
i was trying to add more than one domain in nginx , it works with one domain but multiple not
one domain :
add_header 'Access-Control-Allow-Origin' 'ww.xyz.com';
multiple format didn’ works for me … like
add_header 'Access-Control-Allow-Origin' 'ww.xyz.com, sub.xyz.com ';
add_header 'Access-Control-Allow-Origin' 'ww.xyz.com sub.xyz.com ';

the solution was :
Inside frappe bench folder write :
nano config/nginx.conf

write this code before the server block

  map $http_origin $origin_allowed {
     default 0;
     http://localhost:3000 1;
     https://sub.yourdomain.com 1;
 `#  ... add more allowed origins here`
    }

map $origin_allowed $origin {
  default "";
  1 $http_origin;
}

and inside the server block you want to open the cors in add this line

            if ($request_method = 'OPTIONS') {
                    add_header 'Access-Control-Allow-Origin' $origin;

as you can see $origin is set by the first code block . that way you can add as many sub domain and domains to call your server .

7 Likes

try with https://

add_header Access-Control-Allow-Origin "https://ww.xyz.com https://sub.xyz.com"

Can this feature be added to bench command?

bench setup nginx

Just throwing it out there. I had this multitenant setup serving a few sites and wanted to enable cors just for a few sites.

Let’s say I had a couple sites - site1.com and site2.com (assuming that the site name is the same as the host where it’s reachable at). And I wanted to enable cors from https://some.web.app just for site1.com. I ended up using the following map -

map $http_origin:$host $origin {
        default "";
        https://some.web.app:site1.com $http_origin;
}

Another thing was that I had to

map_hash_bucket_size 128;

But that could be just me. nginx docs says that map_hash_bucket_size “depends on the processor’s cache line size”.

The rest to set add_header could be the same as the one in the OP.

this way worked smoth for me… thanks…