是否有一种方法允许多个跨域使用Access-Control-Allow-Origin头?

我知道*,但它太开放了。我只讲几个域。

举个例子,是这样的:

Access-Control-Allow-Origin: http://domain1.example, http://domain2.example

我已经尝试了上面的代码,但它似乎不能在Firefox中工作。

是否可以指定多个域,还是只能指定一个域?


当前回答

下面是如何回显Origin头,如果它匹配你的域与Nginx,这是有用的,如果你想为一个字体多子域:

location /fonts {
    # this will echo back the origin header
    if ($http_origin ~ "example.org$") {
        add_header "Access-Control-Allow-Origin" $http_origin;
    }
}

其他回答

Django中还有一个答案。要让一个视图允许来自多个域的CORS,以下是我的代码:

def my_view(request):
    if 'HTTP_ORIGIN' in request.META.keys() and request.META['HTTP_ORIGIN'] in ['http://allowed-unsecure-domain.com', 'https://allowed-secure-domain.com', ...]:
        response = my_view_response() # Create your desired response data: JsonResponse, HttpResponse...
        # Then add CORS headers for access from delivery
        response["Access-Control-Allow-Origin"] = request.META['HTTP_ORIGIN']
        response["Access-Control-Allow-Methods"] = "GET" # "GET, POST, PUT, DELETE, OPTIONS, HEAD"
        response["Access-Control-Max-Age"] = "1000"  
        response["Access-Control-Allow-Headers"] = "*"  
        return response

如果你使用字体有困难,可以使用:

<FilesMatch "\.(ttf|ttc|otf|eot|woff)$">
    <IfModule mod_headers>
        Header set Access-Control-Allow-Origin "*"
    </IfModule>
</FilesMatch>

Nginx用户允许多个域的CORS。我喜欢@marshall的例子,尽管他的回答只匹配一个域。为了匹配域和子域的列表,这个正则表达式可以很容易地使用字体:

location ~* \.(?:ttf|ttc|otf|eot|woff|woff2)$ {
   if ( $http_origin ~* (https?://(.+\.)?(domain1|domain2|domain3)\.(?:me|co|com)$) ) {
      add_header "Access-Control-Allow-Origin" "$http_origin";
   }
}

这将只回显与给定域列表匹配的“Access-Control-Allow-Origin”标头。

并非所有浏览器都使用HTTP_ORIGIN。HTTP_ORIGIN有多安全?对我来说,它在FF中是空的。 我有网站,我允许访问我的网站发送一个网站ID,然后我检查我的数据库记录与ID,并获得SITE_URL列值(www.yoursite.com)。

header('Access-Control-Allow-Origin: http://'.$row['SITE_URL']);

即使发送了一个有效的站点ID,请求也需要来自我的数据库中列出的与该站点ID相关的域。

我努力为一个运行HTTPS的域设置这个,所以我想我会分享这个解决方案。我在我的httpd.conf文件中使用了以下指令:

    <FilesMatch "\.(ttf|otf|eot|woff)$">
            SetEnvIf Origin "^http(s)?://(.+\.)?example\.com$" AccessControlAllowOrigin=$0
            Header set Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
    </FilesMatch>

将example.com更改为您的域名。在httpd.conf文件中的<VirtualHost x.x.x.x:xx>中添加此内容。注意,如果你的VirtualHost有一个端口后缀(例如:80),那么这个指令将不适用于HTTPS,所以你还需要去/etc/apache2/sites-available/default-ssl并在那个文件中添加相同的指令,在<VirtualHost _default_:443>部分。

配置文件更新后,需要在终端上执行以下命令:

a2enmod headers
sudo service apache2 reload