Specify Multiple Subdomains with Access Control Origin

后端 未结 7 853
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-13 17:57

I am trying to allow access to every subdomain on my site in order to allow cross subdomain AJAX calls. Is there a way to specify all subdomains of a site like *.example.c

7条回答
  •  梦毁少年i
    2021-02-13 18:28

    Here's how I did it.

    The Origin header is specified by the browser and will contain the domain that requested the script on the other domain:

    Origin: http://www.websiteA.com
    

    Therefore you can "whitelist" multiple domains in your server-side script:

    $allowedOrigins = [
        "http://www.websiteA.com",
        "https://www.websiteB.com"
        // ... etc
    ];
    

    What you can then do is check if the $_SERVER["HTTP_ORIGIN"] global contains a domain within that whitelist:

    if (in_array($_SERVER["HTTP_ORIGIN"], $allowedOrigins)) {
    

    And set the Access-Control-Allow-Origin response header to whatever Origin header value was:

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

    Full script:

    $allowedOrigins = [
        "http://www.websiteA.com",
        "https://www.websiteB.com"
        // ... etc
    ];
    
    if (in_array($_SERVER["HTTP_ORIGIN"], $allowedOrigins)) {
        header("Access-Control-Allow-Origin: " . $_SERVER["HTTP_ORIGIN"]);
    }
    

提交回复
热议问题