16

I want to configure apache to allow XMLHttpRequests from multiple, but not all domains.

This works:

Header set Access-Control-Allow-Origin "*"

But it's unsafe, I want to allow domains specified by me, so after a bit of googling I got to this:

Header set Access-Control-Allow-Origin "http://domain1.com http://domain2.com"

But this only picks up first domain, the second is not allowed. How to properly specify multiple domains?

grucha
  • 719
  • 2
  • 7
  • 14

2 Answers2

41

you can use SetEnvIf in your .htaccess file or in in vhost file (inside "Directory" group):

<IfModule mod_headers.c>
   SetEnvIfNoCase Origin "https?://(www\.)?(mydomain\.com|mydomain2\.com)(:\d+)?$" AccessControlAllowOrigin=$0
   Header set Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
</IfModule>

With this code you can allow access from

  • "mydomain.com" and "mydomain2.com"
  • with or without "www." in front
  • with or without port number
  • http or https

You can add multiple domains separated with | or you can use regexp to configure different subdomains or patterns.

Ema
  • 453
  • 4
  • 6
  • 4
    Great, except mine only worked if I put `Header set` instead of `Header add`. – Matt K Oct 16 '13 at 21:04
  • 2
    Correct me if I'm wrong, but I think you need to remove the $1 from the second line. With it present, any requests over https will fail, because the $1 captures the 's' in https and appends it to the end of the allowed url (so you end up with .coms). – jonathanm Mar 14 '14 at 17:42
  • I see these SetEnvIf solutions everywhere but nobody ever explains **how** they work. – Szczepan Hołyszewski Sep 29 '16 at 17:15
  • Yes, thank you. Worked great in my /sites-available/mysite.conf :D – Andy Nov 08 '16 at 18:45
  • Confirmed this works superbly, note for localhost with port drop the port number off like this: SetEnvIfNoCase Origin "https?://(www\.)?(localhost| – rhysclay Sep 06 '17 at 05:49
-2
Header always append Access-Control-Allow-Origin: "http://domain1.com"
Header always append Access-Control-Allow-Origin: "http://domain2.com"
  • 3
    Add some explanation with answer for how this answer help OP in fixing current issue – ρяσѕρєя K Dec 15 '16 at 09:03
  • This does not work as `Access-Control-Allow-Origin` header only allows one value. So while this would be a valid way of defining multiple values for a header that allowed multiple inputs, this is not one of those cases. – jtimmins Sep 05 '17 at 21:16