Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ajax

apache

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?

like image 831
grucha Avatar asked Feb 27 '12 14:02

grucha


People also ask

Can you have multiple Access-Control allow Origin headers?

More than one Access-Control-Allow-Origin header was sent by the server. This isn't allowed.

How do I set the Access-Control allow Origin header?

Simply add a header to your HttpServletResponse by calling addHeader : response. addHeader("Access-Control-Allow-Origin", "*");

Can HTTP headers be used to restrict or allow access to resources from specified origins?

Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources.


1 Answers

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.

like image 193
Ema Avatar answered Oct 21 '22 17:10

Ema