php 在 .htaccess 中启用 cors
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14467673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
enable cors in .htaccess
提问by Devin Crossman
I have created a basic RESTful service with the SLIM PHP framework and now I'm trying to wire it up so that I can access the service from an Angular.js project. I have read that Angular supports CORS out of the box and all I needed to do was add this line: Header set Access-Control-Allow-Origin "*"to my .htaccess file.
我已经使用 SLIM PHP 框架创建了一个基本的 RESTful 服务,现在我正在尝试将它连接起来,以便我可以从 Angular.js 项目访问该服务。我已经读到 Angular 开箱即用地支持 CORS,我需要做的就是将这一行添加Header set Access-Control-Allow-Origin "*"到我的 .htaccess 文件中。
I've done this and my REST application is still working (no 500 internal server error from a bad .htaccess) but when I try to test it from test-cors.orgit is throwing an error.
我已经这样做了,我的 REST 应用程序仍在工作(没有 500 内部服务器错误来自一个坏的 .htaccess),但是当我尝试从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
My .htaccess file looks like this
我的 .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"
Is there something else I need to add to my .htaccess to get this to work properly or is there another way to enable CORS on my server?
我还需要向我的 .htaccess 添加其他内容才能使其正常工作,还是有另一种方法可以在我的服务器上启用 CORS?
回答by Devin Crossman
Since I had everything being forwarded to index.php anyway I thought I would try setting the headers in PHP instead of the .htaccess file and it worked! YAY! Here's what I added to index.php for anyone else having this problem.
由于我已经将所有内容都转发到 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']}");
}
credit goes to slashingweapon for his answer on this question
感谢 slashingweapon 对这个问题的回答
Because I'm using Slim I added this route so that OPTIONS requests get a HTTP 200 response
因为我使用的是 Slim,所以我添加了这条路由,以便 OPTIONS 请求获得 HTTP 200 响应
// return HTTP 200 for HTTP OPTIONS requests
$app->map('/:x+', function($x) {
http_response_code(200);
})->via('OPTIONS');
回答by markmarijnissen
Should't the .htaccessuse addinstead of set?
不应该.htaccess使用add代替set吗?
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
回答by Hyman Leon
This is what worked for me:
这对我有用:
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"
回答by Santanu Brahma
It's look like you are using an old version of slim(2.x). You can just add following lines to .htaccess and don't need to do anything in PHP scripts.
看起来您使用的是旧版本的 slim(2.x)。您只需将以下几行添加到 .htaccess 中,无需在 PHP 脚本中执行任何操作。
# Enable cross domain access control
SetEnvIf Origin "^http(s)?://(.+\.)?(domain_one\.com|domain_two\.net)$" REQUEST_ORIGIN=<Files "index.php">
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
</Files>
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]
回答by jcubic
As in this answer Custom HTTP Header for a specific fileyou can use <File>to enable CORS for a single file with this code:
正如在这个特定文件的自定义 HTTP 标头答案中,您可以使用<File>以下代码为单个文件启用 CORS:
# Enable cross domain access control
SetEnvIf Origin "^http(s)?://(.+\.)?(1xyz\.com|2xyz\.com)$" REQUEST_ORIGIN=SetEnvIf Origin "http(s)?://(www\.)?(allowed.domain.one|allowed.domain.two)$" AccessControlAllowOrigin=// 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);
});
Header set Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
Header set Access-Control-Allow-Credentials true
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]
回答by levin
Will be work 100%, Apply in .htaccess:
将 100% 工作,在 .htaccess 中申请:
$app = new \Slim\App();
$app->options('/books/{id}', function ($request, $response, $args) {
// Return response headers
});
回答by Karl Adler
Thanks to Devin, I figured out the solution for my SLIM application with multi domain access.
感谢 Devin,我为我的 SLIM 应用程序找到了多域访问的解决方案。
In htaccess:
在 htaccess 中:
##代码##in index.php
在 index.php 中
##代码##回答by Rocío García Luque
I tried @abimelex solution, but in Slim 3.0, mapping the OPTIONS requests goes like:
我尝试了@abimelex 解决方案,但在 Slim 3.0 中,映射 OPTIONS 请求如下:
##代码##https://www.slimframework.com/docs/objects/router.html#options-route
https://www.slimframework.com/docs/objects/router.html#options-route

