是否有一种方法允许多个跨域使用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中工作。
是否可以指定多个域,还是只能指定一个域?
当前回答
我有https://stackoverflow.com/a/7454204/13779574这段代码工作得很好,但当用户进入该页面时给出一个错误。 我用这段代码解决了这个问题。
if (isset($_SERVER['HTTP_ORIGIN'])) {
$http_origin = $_SERVER['HTTP_ORIGIN'];
if ($http_origin == "http://localhost:3000" || $http_origin == "http://api.loc/"){
header("Access-Control-Allow-Origin: $http_origin");
}
}
其他回答
这是我为一个被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头的值,而不是返回*通配符。
我有https://stackoverflow.com/a/7454204/13779574这段代码工作得很好,但当用户进入该页面时给出一个错误。 我用这段代码解决了这个问题。
if (isset($_SERVER['HTTP_ORIGIN'])) {
$http_origin = $_SERVER['HTTP_ORIGIN'];
if ($http_origin == "http://localhost:3000" || $http_origin == "http://api.loc/"){
header("Access-Control-Allow-Origin: $http_origin");
}
}
AWS Lambda/ fire Gateway
有关如何在无服务器AWS Lambda和API网关上配置多个源的信息-尽管一个相当大的解决方案,但人们会觉得应该非常简单-请参阅这里:
https://stackoverflow.com/a/41708323/1624933
目前不可能在API Gateway中配置多个源,请参阅这里:https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors-console.html),但建议(在上面的回答中)是:
检查浏览器发送的Origin报头 在来源白名单上查一下 如果匹配,返回传入的Origin作为Access-Control-Allow-Origin头,否则返回占位符(默认Origin)。
简单的解决方案显然是可行的 所有(*)像这样:
exports.handler = async (event) => {
const response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials" : true // Required for cookies, authorization headers with HTTPS
},
body: JSON.stringify([{
但是在API网关端做这件事可能会更好(见上面的第二个链接)。
匹配子域的PHP代码示例。
if( preg_match("/http:\/\/(.*?)\.yourdomain.example/", $_SERVER['HTTP_ORIGIN'], $matches )) {
$theMatch = $matches[0];
header('Access-Control-Allow-Origin: ' . $theMatch);
}
如果你使用字体有困难,可以使用:
<FilesMatch "\.(ttf|ttc|otf|eot|woff)$">
<IfModule mod_headers>
Header set Access-Control-Allow-Origin "*"
</IfModule>
</FilesMatch>