Jason Varga
Jason Varga

Reputation: 1959

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]

Upvotes: 6

Views: 2557

Answers (3)

Jason Varga
Jason Varga

Reputation: 1959

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]

Upvotes: 6

wprater
wprater

Reputation: 1032

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]

Upvotes: 1

Jon Lin
Jon Lin

Reputation: 143946

Try adding an [OR] flag to your conditions. You really want either no www or no https:

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

Upvotes: 0

Related Questions