简体   繁体   中英

SSL Redirection in CakePHP

当任何用户在cakePHP中键入“ http://www.example.com ”时,我们如何将“ http://www.example.com ”重定向到“ https://www.example.com ”?

You can use a .htacces file to do it before loading any php. Then the servers doesn't need to load the PHP scripts

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L]

While the currently accepted answer focuses on the use of apache's rewrite module, there are a number of cases where this answer doesn't apply, for an obvious example when apache isn't used at all or when rewrite module isn't and can't be enabled.

So a more generic answer would involve you adding this to your AppController

public function beforeFilter(Event $event) {
    if (!env('HTTPS')) {
        return $this->redirect('https://' . $this->request->host() . $this->request->here(), 301);
    }
}

Which would make a permanent redirect to the same url under https if https isn't used.

You don't specify cake's version so the above is cakephp 3 code, just remove Event $event from the function arguments to make it cake 2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM