17

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.example http://domain2.example"

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

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
grucha
  • 759
  • 2
  • 8
  • 14

1 Answers1

43

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\.example|mydomain2\.example)(:\d+)?$" AccessControlAllowOrigin=$0
   Header set Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
</IfModule>

With this code you can allow access from

  • mydomain.example and mydomain2.example
  • 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.

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
Ema
  • 473
  • 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
  • This is the only thing that worked from the entire internet – Gabbr Issimo Jul 26 '23 at 07:45