是否有一种方法允许多个跨域使用Access-Control-Allow-Origin头?
我知道*,但它太开放了。我只讲几个域。
举个例子,是这样的:
Access-Control-Allow-Origin: http://domain1.example, http://domain2.example
我已经尝试了上面的代码,但它似乎不能在Firefox中工作。
是否可以指定多个域,还是只能指定一个域?
是否有一种方法允许多个跨域使用Access-Control-Allow-Origin头?
我知道*,但它太开放了。我只讲几个域。
举个例子,是这样的:
Access-Control-Allow-Origin: http://domain1.example, http://domain2.example
我已经尝试了上面的代码,但它似乎不能在Firefox中工作。
是否可以指定多个域,还是只能指定一个域?
当前回答
匹配子域的PHP代码示例。
if( preg_match("/http:\/\/(.*?)\.yourdomain.example/", $_SERVER['HTTP_ORIGIN'], $matches )) {
$theMatch = $matches[0];
header('Access-Control-Allow-Origin: ' . $theMatch);
}
其他回答
并非所有浏览器都使用HTTP_ORIGIN。HTTP_ORIGIN有多安全?对我来说,它在FF中是空的。 我有网站,我允许访问我的网站发送一个网站ID,然后我检查我的数据库记录与ID,并获得SITE_URL列值(www.yoursite.com)。
header('Access-Control-Allow-Origin: http://'.$row['SITE_URL']);
即使发送了一个有效的站点ID,请求也需要来自我的数据库中列出的与该站点ID相关的域。
这是我为一个被AJAX请求的PHP应用程序所做的
$request_headers = apache_request_headers();
$http_origin = $request_headers['Origin'];
$allowed_http_origins = array(
"http://myDumbDomain.example" ,
"http://anotherDumbDomain.example" ,
"http://localhost" ,
);
if (in_array($http_origin, $allowed_http_origins)){
@header("Access-Control-Allow-Origin: " . $http_origin);
}
如果我的服务器允许请求源,返回$http_origin本身作为Access-Control-Allow-Origin头的值,而不是返回*通配符。
听起来,推荐的方法是让服务器从客户端读取Origin头,将其与您希望允许的域列表进行比较,如果匹配,则将Origin头的值作为响应中的Access-Control-Allow-Origin头回显给客户端。
使用.htaccess,你可以这样做:
# ----------------------------------------------------------------------
# Allow loading of external fonts
# ----------------------------------------------------------------------
<FilesMatch "\.(ttf|otf|eot|woff|woff2)$">
<IfModule mod_headers.c>
SetEnvIf Origin "http(s)?://(www\.)?(google.com|staging.google.com|development.google.com|otherdomain.example|dev02.otherdomain.example)$" AccessControlAllowOrigin=$0
Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
Header merge Vary Origin
</IfModule>
</FilesMatch>
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
也许我错了,但据我所知,Access-Control-Allow-Origin有一个“origin-list”作为参数。
根据定义,origin-list为:
origin = "origin" ":" 1*WSP [ "null" / origin-list ]
origin-list = serialized-origin *( 1*WSP serialized-origin )
serialized-origin = scheme "://" host [ ":" port ]
; <scheme>, <host>, <port> productions from RFC3986
由此,我认为不同的起源是被承认的,并且应该被空间分隔开。