I have a site that has some strict requirements for SEO purposes.
The main one is redirecting all http requests to https which I have done by adding this into the AppController:
public function forceSSL() {
return $this->redirect('https://' . env('SERVER_NAME') . $this->here);
}
public function beforeFilter() {
$this->Security->blackHoleCallback = 'forceSSL';
$this->Security->requireSecure();
}
The issue I have is with 404 pages, they do not redirect to https (eg. www.hublink.net/asdfg)
I have also added these 2 lines to the .htaccess file (from another post), and removed the above code but then get a "redirect loop" error
RewriteCond %{HTTPS} !=on [NC]
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
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
See https://wiki.apache.org/httpd/RewriteHTTPToHTTPS It worked for me.
in Controller/AppController.php
This code is working for my CakePHP 3.8
use Cake\Routing\Router;
and
public function initialize()
{
parent::initialize();
if(env('REQUEST_SCHEME')=='http')
{
return $this->redirect('https://www.' . env('SERVER_NAME') . Router::url($this->request->getRequestTarget()));
}else{
$split=explode('.',env('SERVER_NAME'));
if($split[0]!='www'){
return $this->redirect('https://www.' . env('SERVER_NAME') . Router::url($this->request->getRequestTarget()));
}
}
}
I have this in my .htaccess file and it works great. I have it ignoring local and staging URLs, like if I had http://local.example.com it will not force redirection for that url. Those lines can be removed. I like using the .htaccess approach over the one in the AppController. This is also the top level .htaccess file in a standard CakePHP install on a shared hosting environment. There are three .htaccess files in a normal Cakephp install.
<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>
Check your hosting environment and make sure your allowed to have .htaccess files. Need to make sure ModRewrite is installed and working as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With