Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access-Control-Allow-Origin wildcard subdomains, ports and protocols

Tags:

cors

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:*/*

like image 276
Elie Avatar asked Dec 22 '12 13:12

Elie


People also ask

Can I use wildcard in Access-Control allow origin?

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.

How do I enable wildcard subdomains?

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.

Does CORS work with 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.


2 Answers

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.

like image 167
monsur Avatar answered Oct 09 '22 00:10

monsur


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).

like image 41
Noyo Avatar answered Oct 08 '22 23:10

Noyo