Access-Control-Allow-Origin Multiple Origin Domains?

前端 未结 30 2094
隐瞒了意图╮
隐瞒了意图╮ 2020-11-21 07:08

Is there a way to allow multiple cross-domains using the Access-Control-Allow-Origin header?

I\'m aware of the *, but it is too open. I rea

相关标签:
30条回答
  • 2020-11-21 07:25

    If you are having trouble with fonts, use:

    <FilesMatch "\.(ttf|ttc|otf|eot|woff)$">
        <IfModule mod_headers>
            Header set Access-Control-Allow-Origin "*"
        </IfModule>
    </FilesMatch>
    
    0 讨论(0)
  • 2020-11-21 07:26

    We can also set this in Global.asax file for Asp.net application.

    protected void Application_BeginRequest(object sender, EventArgs e)
        {
    
        // enable CORS
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "https://www.youtube.com");
    
        }
    
    0 讨论(0)
  • 2020-11-21 07:27

    For multiple domains, in your .htaccess:

    <IfModule mod_headers.c>
        SetEnvIf Origin "http(s)?://(www\.)?(domain1.example|domain2.example)$" AccessControlAllowOrigin=$0$1
        Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
        Header set Access-Control-Allow-Credentials true
    </IfModule>
    
    0 讨论(0)
  • 2020-11-21 07:28

    PHP Code:

    $httpOrigin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : null;
    if (in_array($httpOrigin, [
        'http://localhost:9000', // Co-worker dev-server
        'http://127.0.0.1:9001', // My dev-server
    ])) header("Access-Control-Allow-Origin: ${httpOrigin}");
    header('Access-Control-Allow-Credentials: true');
    
    0 讨论(0)
  • 2020-11-21 07:30

    A more flexible approach is to use Apache 2.4's expressions. You can match against domains, paths, and just about every other request variable. Though the response sent is always *, the only requesters receiving it are the ones that meet the requirements anyway. Using the Origin (or any other) request header in the expression causes Apache to automatically merge it into the Vary response header, so that response won't be reused for a different origin.

    <IfModule mod_headers.c>
        <If "%{HTTP:Host} =~ /\\bcdndomain\\.example$/i && %{HTTP:Origin} =~ /\\bmaindomain\\.example$/i">
            Header set Access-Control-Allow-Origin "*"
        </If>
    </IfModule>
    
    0 讨论(0)
  • 2020-11-21 07:31

    Here's how to echo the Origin header back if it matches your domain with Nginx, this is useful if you want to serve a font multiple sub-domains:

    location /fonts {
        # this will echo back the origin header
        if ($http_origin ~ "example.org$") {
            add_header "Access-Control-Allow-Origin" $http_origin;
        }
    }
    
    0 讨论(0)
提交回复
热议问题