Set Access-Control-Allow-Origin in nginx using wildcard domain

Solution 1:

you have to do it with an if condition

location /  {
  set $cors "";
  if ($http_origin ~* (\.mydomain\.com|\.myseconddomain\.com)$) {
      set $cors "true";
  }

  proxy_pass http://backend:10005/apathifyouwantso/;

  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';
  }
}

Solution 2:

You sure can. I use the following directive to support some of our cross domain fonts:

  add_header Access-Control-Allow-Origin *;

Solution 3:

Setting "Access-Control-Allow-Origin" based on conditions in nginx is very dangerous and you should be careful. The answer above is opening a security vulnerability.

if ($http_origin ~* (\.mydomain\.com|\.myseconddomain\.com)) 

This line will match something.mydomain.com and also something.mydomain.com.anyotherdomain.com (A domain anyone can create)

Doing this, will allow the following scenario:

  1. A banner makes users open something.mydomain.com.anyotherdomain.com
  2. Which makes requests to your site using fetch.
  3. Fetch, can include credentials, which means your user cookies.
  4. So the attacker can make requests to your server authenticated as that user. (Ex: send messages, emails, etc)

And all of that, because the regular expression is missing one '$' at the end.

if ($http_origin ~* (\.mydomain\.com|\.myseconddomain\.com)$) 

Thats not the only way you can make that particular regexp bad, thats why I am explaining the problem, rather than just adding $ in the previous answer