Skip to content
Advertisement

Specify Multiple Subdomains with Access Control Origin

I am trying to allow access to every subdomain on my site in order to allow cross subdomain AJAX calls. Is there a way to specify all subdomains of a site like *.example.com or alternatively, why does the following not work when I have more than one domain listed:

header('Access-Control-Allow-Origin: http://api.example.com http://www.example.com');

I have read through the following question which appears to be similar, if not the same as this one, other than the fact that I want access to subdomains and this one refers to general domains.

Access-Control-Allow-Origin Multiple Origin Domains?

If the above question is the solution to this problem, then how am I able to retrieve the origin from the header. It appears that $_SERVER[‘HTTP_ORIGIN’] is very unreliable and not even cross browser. I need to be able to see the origin in any browser that may show an error when trying to send an AJAX call using javascript.

Advertisement

Answer

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']);
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement