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.example:8080/
to https://www.mywebsite.example/*
Typically, I'd like to enable request from origins matching (and limited to):
//*.mywebsite.example:*/*
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\.example(?::\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.example
) in addition to all its subdomains can simply replace the regular expression in the first line with this one:
^(https?://(?:.+\.)?mywebsite\.example(?::\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).