I'm trying to enable CORS for all subdomains, ports and protocol.
For example, I want to be able to run an XHR request from http://sub.mywebsite.com:8080/ to https://www.mywebsite.com/*
Typically, I'd like to enable request from origins matching (and limited to):
//*.mywebsite.com:*/*
Access-Control-Allow-Origin specifies either a single origin which tells browsers to allow that origin to access the resource; or else — for requests without credentials — the " * " wildcard tells browsers to allow any origin to access the resource.
In other words, with a wildcard subdomain, it will not matter whether someone accesses your site through ww.yourdomain.com or wwwwww.yourdomain.com, they will still be taken to your home page. To enable the wildcard subdomain, go to your Site Tools > Domain > Subdomains.
Yes you have to enable it. You have to send CORS allow headers from server side to your browser. This is because a subdomain counts as a different origin. You probably have to allow HTTP methods like PUT, DELETE, OPTIONS as well.
The CORS spec is all-or-nothing. It only supports *
, null
or the exact protocol + domain + port: http://www.w3.org/TR/cors/#access-control-allow-origin-response-header
Your server will need to validate the origin header using the regex, and then you can echo the origin value in the Access-Control-Allow-Origin
response header.
Based on DaveRandom's answer, I was also playing around and found a slightly simpler Apache solution that produces the same result (Access-Control-Allow-Origin
is set to the current specific protocol + domain + port dynamically) without using any rewrite rules:
SetEnvIf Origin ^(https?://.+\.mywebsite\.com(?::\d{1,5})?)$ CORS_ALLOW_ORIGIN=$1 Header append Access-Control-Allow-Origin %{CORS_ALLOW_ORIGIN}e env=CORS_ALLOW_ORIGIN Header merge Vary "Origin"
And that's it.
Those who want to enable CORS on the parent domain (e.g. mywebsite.com) in addition to all its subdomains can simply replace the regular expression in the first line with this one:
^(https?://(?:.+\.)?mywebsite\.com(?::\d{1,5})?)$
.
Note: For spec compliance and correct caching behavior, ALWAYS add the Vary: Origin
response header for CORS-enabled resources, even for non-CORS requests and those from a disallowed origin (see example why).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With