cakephp and https redirects

djcamo picture djcamo · Aug 13, 2014 · Viewed 22.8k times · Source

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]

Answer

Fred Noriega picture Fred Noriega · Feb 7, 2015
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.