Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access-Control-Allow-Origin for multiple domains, in an easier way

header('Access-Control-Allow-Origin: http://splash.example.com');
header('Access-Control-Allow-Credentials: true');

Hello again Stackoverflow!

On my website, I have an ajax file ajax.php, where I need multiple (sub) domains to access it and fire requests.

The problem is that it works for splash.example.com and example.com with the solution posted above, and this in the request:

$.ajax({
    ...

    crossDomain: true,
    xhrFields: {
        withCredentials: true
    },

    ...
});

But isn't there an easier way? 'Cause right now it isn't working for www.example.com, even with the solution posted above.

I've tried putting this in my htaccess:

<IfModule mod_headers.c>
    Header add Access-Control-Allow-Origin "http://example.com"
    Header add Access-Control-Allow-Origin "http://www.example.com"
    Header add Access-Control-Allow-Origin "http://splash.example.com"
    Header set Access-Control-Allow-Credentials true
</IfModule>

but this didn't work somehow.

Can you guys help me?

like image 903
Thew Avatar asked Oct 22 '13 13:10

Thew


1 Answers

The preferred method would be to read the request header, find the origin, check it in your server side code. If the domain is allowed to access the page, send back the origin domain in one single Access-Control-Allow-Origin header.

Another pro: No other domain user would see the list of allowed domains. Every user would only see his own domain (if allowed).

like image 65
devnull69 Avatar answered Sep 19 '22 02:09

devnull69