我开发了一个cakephp网站,应该对所有网页使用ssl。它按预期工作,除非我在控制器中使用重定向,它重定向到http://subdomain.domain.com而不是https://subdomain.domain.com/controller/action。
我通过为端口80创建指向cakephp应用程序的虚拟主机并在.htaccess中添加了这些重写规则来解决这个问题
RewriteCond%{HTTPS}关闭 RewriteRule(。*)https://% {HTTP_HOST}%{REQUEST_URI} [L]
这会捕获这种情况并重定向到https,但这会给服务器带来不必要的额外流量。
此额外流量的原因是重定向功能,因为它会生成错误的网址。我查看了redirect函数,并调用router :: url来创建实际的url。但是,我无法弄清楚如何或在何处指示路由器使用https而不是http。
添
答案 0 :(得分:5)
我正在做一些猜测,但我怀疑这是一个非常糟糕的RewriteRule。
你应该“重定向”而不是“重写”。 Cake生成的链接通常是相对于root的,所以除非你将“true”作为第二个参数传递,否则不要指定协议。
我也有apache在80和443上进行监听,这样我至少可以回复不正确的请求。
这是我在AppController类中执行相同操作的代码:
function beforeFilter() {
parent::beforeFilter();
$this->_setupSecurity();
}
function _setupSecurity() {
$this->Security->blackHoleCallback = '_badRequest';
if(Configure::read('forceSSL')) {
$this->Security->requireSecure('*');
}
}
/**
* The main SecurityComponent callback.
* Handles both missing SSL problems and general bad requests.
*/
function _badRequest() {
if(Configure::read('forceSSL') && !$this->RequestHandler->isSSL()) {
$this->_forceSSL();
} else {
$this->cakeError('error400');
}
exit;
}
/**
* Redirect to the same page, but with the https protocol and exit.
*/
function _forceSSL() {
$this->redirect('https://' . env('SERVER_NAME') . $this->here);
exit;
}
我在bootstrap.php中也有自己的配置'forceSSL'选项,用于根据环境打开和关闭它,因此需要将其设置为true才能使上述工作正常。
答案 1 :(得分:0)
我发现错误是Apache的配置错误。
尝试使用Jamies解决方案,该站点最终处于重定向循环,因为即使请求是https,RequestHandler-> isSSL()也返回false。然后我发现$ _SERVER ['https']没有设置,$ _SERVER ['port']是80,而不是预期的443。
此时我已将我的ssl指令放在sites-available / default,
中
SSLEngine on
SSLCertificateFile [path to cert file]
SSLCertificateKeyFile [path to keyfile]
使用重定向循环将ssl指令移动到子域的虚拟主机解决了这个问题。
实际上也解决了我的初始问题,因为方法Router :: url检查$ _SERVER ['https']如果设置它会生成一个以https开头的url:否则只是http:
我已经在.htaccess中测试了Jameies解决方案和我自己的重写规则,并且在修复后它们都按预期工作。
添
答案 2 :(得分:0)
它的例子已在CookBook中提到过 http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html#usage
class AppController extends Controller {
// Add security component
public $components = array('Security');
public function beforeFilter() {
$this->Security->blackHoleCallback = 'forceSSL';
$this->Security->requireSecure();
}
// Add this function in your AppController
public function forceSSL() {
return $this->redirect('https://' . env('SERVER_NAME') . $this->here);
}
}