在.htaccess中启用cors


71

我已经使用SLIM PHP框架创建了一个基本的RESTful服务,现在我试图将其连接起来,以便可以从Angular.js项目访问该服务。我已经知道Angular开箱即用地支持CORS,而我要做的就是Header set Access-Control-Allow-Origin "*"在我的.htaccess文件中添加以下行:

我已经做到了,我的REST应用程序仍然可以正常工作(.htaccess错误导致500个内部服务器没有错误),但是当我尝试从test-cors.org对其进行测试时,它抛出了错误。

Fired XHR event: loadstart
Fired XHR event: readystatechange
Fired XHR event: error

XHR status: 0
XHR status text: 
Fired XHR event: loadend

我的.htaccess文件如下所示

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ /index.php [QSA,L]
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"

我还需要添加其他东西到.htaccess中才能使其正常工作,还是有另一种方法可以在服务器上启用CORS?


Answers:


95

因为无论如何我都将所有内容转发到index.php,所以我想我会尝试在PHP中设置标头,而不是.htaccess文件,并且它起作用了!好极了!这是我添加到index.php的其他任何有此问题的人。

// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
    // should do a check here to match $_SERVER['HTTP_ORIGIN'] to a
    // whitelist of safe domains
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');    // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");         

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

}

这个问题的答案归功于slashingweapon

因为我使用的是Slim,所以我添加了此路由,以便OPTIONS请求获得HTTP 200响应

// return HTTP 200 for HTTP OPTIONS requests
$app->map('/:x+', function($x) {
    http_response_code(200);
})->via('OPTIONS');

1
到目前为止,您已经挽救了四命,甚至以为我只需要header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");。谢谢 !
raph77777

2
查看了其他答案后,我对您的解决方案感到担忧。作者slashingweapon包含了一条已删除的注释,该注释提示您添加一些逻辑以确定原点是否是受信任的原点。在这里,您已盲目删除它,接受任何来源。不好的做法。

1
@乔好点。我用评论检查原点的方式更新了答案
Devin Crossman

84

应该.htaccess使用add代替set吗?

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"

1
谢谢!这解决了我的问题!我正在使用set,但没有用,用添加修复后更改了它。对于它的价值,这是在wordpress博客上完成的,并且在.htaccess文件中还有其他内容
BBog 2014年

1
此处的文档说“设置” enable-cors.org/server_apache.html。大概引起了很多问题!
Ryan How

我从设置更改为添加,但仍然收到预检响应,该请求具有无效的HTTP状态代码400 ..pls建议..已在此处描述了我的完整文章: magento.stackexchange.com/questions/170342/…–
Sushivam

对我来说,第一行就足够了。另外,我猜第二行应该没有冒号?
kslstn

这是最好的答案!!
晃VU TGTT

24

这对我有用:

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"


9

将工作100%,在.htaccess中应用:

# Enable cross domain access control
SetEnvIf Origin "^http(s)?://(.+\.)?(1xyz\.com|2xyz\.com)$" REQUEST_ORIGIN=$0
Header always set Access-Control-Allow-Origin %{REQUEST_ORIGIN}e env=REQUEST_ORIGIN
Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
Header always set Access-Control-Allow-Headers "x-test-header, Origin, X-Requested-With, Content-Type, Accept"

# Force to request 200 for options
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule .* / [R=200,L]

还要补充一下,有必要编辑SetEnvIf语句,定义允许CORS的远程服务器(1xyz.com,2xyz.com)。
user1298923

8

好像您正在使用旧版本的slim(2.x)。您可以在.htaccess中添加以下行,而无需在PHP脚本中执行任何操作。

# Enable cross domain access control
SetEnvIf Origin "^http(s)?://(.+\.)?(domain_one\.com|domain_two\.net)$" REQUEST_ORIGIN=$0
Header always set Access-Control-Allow-Origin %{REQUEST_ORIGIN}e env=REQUEST_ORIGIN
Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE"
Header always set Access-Control-Allow-Headers: Authorization

# Force to request 200 for options
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule .* / [R=200,L]

2

多亏了Devin,我才找到了适用于我的具有多域访问权限的SLIM应用程序的解决方案。

在htaccess中:

SetEnvIf Origin "http(s)?://(www\.)?(allowed.domain.one|allowed.domain.two)$" AccessControlAllowOrigin=$0$1
Header set Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
Header set Access-Control-Allow-Credentials true

在index.php中

// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");         

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
}
// instead of mapping:
$app->options('/(:x+)', function() use ($app) {
    //...return correct headers...
    $app->response->setStatus(200);
});

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.