With nginx can I specify Access-Control-Allow-Origin using a wildcard like *.mydomain.com?

Would it look like:

add_header Access-Control-Allow-Origin *.mydomain.com;



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

  add_header Access-Control-Allow-Origin *;
  • 3
    No I don't want wildcard for everything, but only anything.mydomain.com. I have a SaaS and each signup get's their own subdomain (user.mydomain.com). Also, I am testing and put add_header Access-Control-Allow-Origin http://google.com; for testing, and assumed requests would fail, but surprisingly they still work. Any idea why? They should fail right? – Justin Feb 5 '13 at 20:13
  • Ah, I understand. Yes, you can use globs, though I can't say for certain why requests aren't failing like they should. The very long answer on how to use Access-Control is here: w3.org/TR/2008/WD-access-control-20080912 – Stephan Feb 5 '13 at 20:18
  • 2
    Actually further research, shows that Access-Control-Allow-Origin only supports * and a full host, i.e. wildcard domains are NOT supported. However still not sure why requests are working when I set: add_header Access-Control-Allow-Origin https://google.com; – Justin Feb 5 '13 at 20:24
  • Ah, seems I learned something as well then! – Stephan Feb 5 '13 at 20:27

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.