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.
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:Therefore you can "whitelist" multiple domains in your server-side script:
What you can then do is check if the
$_SERVER["HTTP_ORIGIN"]
global contains a domain within that whitelist:And set the
Access-Control-Allow-Origin
response header to whateverOrigin
header value was:Full script:
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 theAccess-Control-Allow-Origin
like so:I tried using this approach to achieve constraint on a specific domain basis:
I hope it works.
While the answer works, it does defeat the purpose of the whole thing, since it allows requests from any host.
I use something like: