handle multiple domains with Access-Control-Allow-Origin header in Apache
For 3 domains, in your .htaccess:
<IfModule mod_headers.c> SetEnvIf Origin "http(s)?://(www\.)?(domain1.org|domain2.com|domain3.net)$" AccessControlAllowOrigin=$0$1 Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin Header set Access-Control-Allow-Credentials true</IfModule>
I've tried this and it works for me. Let me know if it doesn't for you.
Unless I'm misunderstanding the manual, it should be:
Header always append Access-Control-Allow-Origin: "example1.com"Header always append Access-Control-Allow-Origin: "example2.com"Header always append Access-Control-Allow-Origin: "example3.com"
The manual states that the set
and add
actions behave in the following way:
set: "The response header is set, replacing any previous header with this name"
add: "...This can result in two (or more) headers having the same name. This can lead to unforeseen consequences..."
To restrict access to certain URIs checkout these docs:
Server-Side Access Control#Apache_examples
One helpful trick is to use an Apache rewrite, environment variable, and headers to apply Access-Control-Allow-* to certain URIs. This is useful, for example, to constrain cross-origin requests to GET /api(.*).json requests without credentials:
RewriteRule ^/api(.*)\.json$ /api$1.json [CORS=True]Header set Access-Control-Allow-Origin "*" env=CORSHeader set Access-Control-Allow-Methods "GET" env=CORSHeader set Access-Control-Allow-Credentials "false" env=CORS
Also, in general, according to W3 Wiki - CORS Enabled#For_ApacheTo expose the header, you can add the following line inside Directory, Location, and Files sections, or within an .htaccess file.
<IfModule mod_headers.c> Header set Access-Control-Allow-Origin "*"</IfModule>
AND, you can use add rather than set, but be aware that add can add the header multiple times, so it's generally safer to use set.