Specify Multiple Subdomains with Access Control Origin Specify Multiple Subdomains with Access Control Origin ajax ajax

Specify Multiple Subdomains with Access Control Origin


The solution to this issue is to use the $_SERVER['HTTP_ORIGIN'] variable to determine whether the request has come from an allowed domain, and then conditionally set the Access-Control-Allow-Origin like so:

$allowed_domains = [/* Array of allowed domains*/];if (in_array($_SERVER['HTTP_ORIGIN'], $allowed_domains)) {    header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);}


Here's how I did it.

The Origin header is specified by the browser and will contain the domain that requested the script on the other domain:

Origin: http://www.websiteA.com

Therefore you can "whitelist" multiple domains in your server-side script:

$allowedOrigins = [    "http://www.websiteA.com",    "https://www.websiteB.com"    // ... etc];

What you can then do is check if the $_SERVER["HTTP_ORIGIN"] global contains a domain within that whitelist:

if (in_array($_SERVER["HTTP_ORIGIN"], $allowedOrigins)) {

And set the Access-Control-Allow-Origin response header to whatever Origin header value was:

header("Access-Control-Allow-Origin: " . $_SERVER["HTTP_ORIGIN"]);

Full script:

$allowedOrigins = [    "http://www.websiteA.com",    "https://www.websiteB.com"    // ... etc];if (in_array($_SERVER["HTTP_ORIGIN"], $allowedOrigins)) {    header("Access-Control-Allow-Origin: " . $_SERVER["HTTP_ORIGIN"]);}


While the answer works, it does defeat the purpose of the whole thing, since it allows requests from any host.

I use something like:

if(isset($_SERVER['HTTP_ORIGIN'])) {  $origin = $_SERVER['HTTP_ORIGIN'];  if($origin == 'https://sub1.my-website.com' OR $origin == 'https://sub2.my-website.com') {    header("Access-Control-Allow-Origin: $origin");  }}