grucha
grucha

Reputation: 769

How to configure Apache to handle multiple domains with Access-Control-Allow-Origin header?

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?

Upvotes: 18

Views: 26465

Answers (1)

Ema
Ema

Reputation: 493

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.

Upvotes: 45

Related Questions