Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force SSL and WWW together using htaccess

I'm trying to run my entire site through https and force www.

I've seen a number of solutions that provide forcing either www or https, and even a few combined, but I can't seem to get any to work. I usually find myself in a redirect loop.

The closest I've got is the following, but it's not close enough yet:

RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]

I need https://www.example.com/

http://example.com SUCCESS
https://example.com SUCCESS
http://www.example.com FAIL
https://www.example.com SUCCESS, although there's no actual redirection.

Thanks

Update
The following code successfully performs the redirection I require:

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

RewriteCond %{ENV:HTTPS} on [NC]
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]
like image 436
Jason Varga Avatar asked Aug 01 '12 20:08

Jason Varga


2 Answers

Forcing https and www is done by a combination of other provided answers.

This seems to work:

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

RewriteCond %{ENV:HTTPS} on [NC]
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]
like image 170
Jason Varga Avatar answered Sep 18 '22 03:09

Jason Varga


Try this condition instead, it should force the site into ssl for your domain

RewriteCond %{ENV:HTTPS} !on [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]
like image 44
wprater Avatar answered Sep 21 '22 03:09

wprater