For security reason, browser doesn’t allow website to load javascript from other domains by default. It is known as javascript cross domain problem. I remembered that I wrote another post to talk about this when I was working on a iOS project, Ajax HTTPs Reuqest in iOS UIWebview. In that article, I have given 4 solutions for that. Today, I will talk about another issue basing on one of the solution, the Access-Control-Allow-Origin. Before we talk in deep, first let me describe my problem first.

Access Control Allow Origin Multiple Domains Issue

Here I have a javascript file hosted on my website jmsliu.com. When I want to allow another website (let’s say, a.com) to load it. Then, I just add following information in the response http header.

Access-Control-Allow-Origin: http://a.com

Now, there is another website (let’s say, b.com) also want to load this javascript file. For security reason, wildcard is not allowed. Then how to make both websites to be able to load the javascript?

.htaccess solution for Apache Server

If you are search “access-control-allow-origin multiple domains” on google, the first answer is by using .htaccess file provided on stackoverflow (check this link). Here I will not repeat the answer. I just want to point out the problem in this solution.

.htaccess file is only working in Apache server. If the web server is Nginx, this solution will not be applicable.

Access-Control-Allow-Origin for Multiple Domains in Nginx

If you are carefully enough, you may find the solution at the same link.

PHP Solution

Basically, the PHP solution is depending on what web server it is running on. In most of the case, people like to use following code:

header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);

However, most of the time, $_SERVER[‘HTTP_ORIGIN’] is empty, especially when the web server is Nginx. So we can use $_SERVER[‘HTTP_REFERER’] instead. Here is one example source code:

$urlComponent = parse_url($_SERVER['HTTP_REFERER']);
$originURL = $urlComponent["scheme"]."://".$urlComponent["host"];
if(isset($urlComponent["port"])) {
    $originURL .= ":".$urlComponent["port"];
}

header('Access-Control-Allow-Origin: '.$originURL);

When using this code, please make sure that $_SERVER[‘HTTP_REFERER’] is set on your server.

Previous PostNext Post

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *