Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

force SSL+WWW in CakePHP .htaccess

I know the topic "How to force HTTPS + WWW" is often discussed and solved, and in general it works for me.

But as I now got a specific predefined .htaccess from CakePHP I do not know how to include it.

.htaccess for CakePHP:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]

If I put the normal code for HTTPS/WWW Forcing in front or backwards to that code, it does not work properly because all requests are set to root directory and not to e.g. /contact.

Normally I am using:

RewriteCond %{HTTPS} !on [OR]
RewriteCond %{HTTP_HOST} !^www\.mydomain\.com$ [NC]
RewriteRule ^ https://www.mydomain.com%{REQUEST_URI} [R=301]

But you can not just include that above...

Could anybody please help me including HTTPS/WWW Forcing in the above .htaccess?

like image 825
Bob Avatar asked Dec 28 '22 14:12

Bob


2 Answers

The generic way is:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{HTTPS} !on
    RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f    
    RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>

No need to hard-code domain name. Also request will not redirect to root when switching from http to https

like image 67
gins t Avatar answered Jan 12 '23 12:01

gins t


Thanks LazyOne, this maybe working, but for me it often ended up in "mydomain.com/redirect:/app/webroot/index.php" which was really strange. But maybe this is due to the "{REQUEST_URI}" because I had to change my

RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]

to

RewriteRule ^(.*)$ index.php [QSA,L]

due to strange problems with redirect (no idea what happend, CakePHP suddenly requestet a "Redirect:Controller" as also described here http://groups.google.com/group/croogo/browse_thread/thread/55539dabfd0191fd?pli=1 - any idea about this?).

It is now working with this code:

RewriteCond %{HTTP_HOST} ^mydomain.com
RewriteRule (.*) https://www.mydomain.com/$1 [R=301,L]   

RewriteCond %{HTTPS} !on
RewriteRule (.*) https://www.mydomain.com/$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f    
RewriteRule ^(.*)$ index.php [QSA,L]
like image 22
Bob Avatar answered Jan 12 '23 10:01

Bob