在.htaccess中启用cors

mznpcxlj  于 2022-11-16  发布在  其他
关注(0)|答案(9)|浏览(187)

我已经使用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?

g9icjywg

g9icjywg1#

因为我已经把所有的东西都转发到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在this question上给出的答案
因为我使用的是Slim,所以我添加了此路由,以便OPTIONS请求获得HTTP 200响应

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

krcsximq2#

.htaccess不应该使用add而不是set吗?

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

ikfrs5lh3#

这就是我的工作:

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"
xdnvmnnf

xdnvmnnf4#

在此答案Custom HTTP Header for a specific file中,您可以使用<File>为单个文件启用CORS,代码如下:

<Files "index.php">
  Header set Access-Control-Allow-Origin "*"
  Header set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
</Files>

您可以放置特定来源(协议+域+可选端口),而不是"*"

3df52oht

3df52oht5#

将工作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]
j2qf4p5b

j2qf4p5b6#

看起来你使用的是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]
t0ybt7op

t0ybt7op7#

多亏了迪文,我为我的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);
});
w41d8nur

w41d8nur8#

我尝试了@abimelex解决方案,但在Slim 3.0中,MapOPTIONS请求如下所示:

$app = new \Slim\App();
$app->options('/books/{id}', function ($request, $response, $args) {
    // Return response headers
});

https://www.slimframework.com/docs/objects/router.html#options-route

apeeds0o

apeeds0o9#

对于ubuntu用户:
您必须使用以下命令首先激活标头模块:

sudo a2enmod headers

然后通过以下方式重新启动Apache:

sudo service apache2 restart

然后将以下头文件添加到htaccess中:

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

相关问题