cakephp和https重定向

djc*_*amo 10 ssl https cakephp litespeed cakephp-2.0

我有一个网站对SEO目的有一些严格的要求.

主要的是将所有http请求重定向到https,我已经通过将其添加到AppController中来完成:

public function forceSSL() {
    return $this->redirect('https://' . env('SERVER_NAME') . $this->here);
}

public function beforeFilter() {
    $this->Security->blackHoleCallback = 'forceSSL';
    $this->Security->requireSecure();
}
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是404页面,它们不会重定向到https(例如www.hublink.net/asdfg)

我还将这两行添加到.htaccess文件中(来自另一篇文章),并删除了上面的代码,但后来出现"重定向循环"错误

RewriteCond %{HTTPS} !=on [NC]
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
Run Code Online (Sandbox Code Playgroud)

小智 16

RewriteEngine On
# This will enable the Rewrite capabilities

RewriteCond %{HTTPS} !=on
# This checks to make sure the connection is not already HTTPS

RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R=301,L]
# This rule will redirect users from their original location, to the same location but using HTTPS.
# i.e.  http://www.example.com/foo/ to https://www.example.com/foo/
# The leading slash is made optional so that this will work either in httpd.conf
# or .htaccess context
Run Code Online (Sandbox Code Playgroud)

请参阅https://wiki.apache.org/httpd/RewriteHTTPToHTTPS 它对我有用.


dar*_*pes 9

我在.htaccess文件中有这个,效果很好.我忽略了本地和暂存网址,就像我有http://local.example.com它不会强制重定向该网址.这些行可以删除.我喜欢使用.htaccess方法而不是AppController中的方法.这也是共享托管环境中标准CakePHP安装中的顶级.htaccess文件.普通的Cakephp安装中有三个.htaccess文件.

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteBase /

    # FORCE SSL REDIRECTION
    RewriteCond %{ENV:HTTPS} !on [NC]
    RewriteCond %{HTTP_HOST} !^local [NC]
    RewriteCond %{HTTP_HOST} !^staging [NC]
    RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]

    RewriteRule ^$ app/webroot/ [L]
    RewriteRule (.*) app/webroot/$1 [L]
</IfModule>
Run Code Online (Sandbox Code Playgroud)

检查您的托管环境,并确保您允许拥有.htaccess文件.需要确保ModRewrite已安装并正常工作.

  • 谢谢你,不幸的是,一旦我编辑.htaccess文件,我仍然会收到"此网页有重定向循环"错误将与托管公司核对ModRewrite (4认同)

小智 5

所以我找不到一个好方法强制我的整个网站https而不会得到重定向循环和错误.如果您修改该页面的单个控制器,这将在页面级别上工作).无论如何,这是我在弄乱了几天之后最终做的事情.

在我的AppController.php中的controllers文件夹中,我将以下代码直接放在:

public function beforeFilter(){

=================================

 // Force to SSL
 $this->request->addDetector('ssl', array(
    'env' => 'HTTP_X_FORWARDED_PROTO',
    'value' => 'https'
));
if($_SERVER['HTTP_X_FORWARDED_PROTO'] == "http") {  return $this->redirect('https://' . env('SERVER_NAME') . $this->here); }
Run Code Online (Sandbox Code Playgroud)

所以这样做首先要检查它是http还是https.如果它是http,那么我将页面重定向到它的https版本.通过将它放在AppController.php控制器中...这将保护整个站点.

希望这能帮助那些也在苦苦挣扎的人.