Take the 2-minute tour ×
Webmasters Stack Exchange is a question and answer site for pro webmasters. It's 100% free, no registration required.

I'm looking for a way to force SSL and www.

I've been able to force both separately but together I keep running into redirection issues. The following code works when handling a URL in this format: http://example.com and properly redirects to https://www.example.com but when the incoming URL is https://example.com it will not forward to https://www.example.com - Any suggestions?

EDIT: it should also send http://www.example.com to https://www.example.com.

RewriteCond %{REMOTE_ADDR} !127\.0\.0\.0
RewriteCond %{SERVER_PORT} 80
RewriteCond %{HTTP_HOST} !^www.example\.com$
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]
share|improve this question
add comment

3 Answers

The first line is used to prevent internal URL's from being rewritten. That might cause different pages to be displayed, so I've removed it.

If the host is example.com or is not requested over HTTPS, it will be rewritten to https://example.com/. I.e., it rewrites http://example.com, http://www.example.com and https://example.com to https://www.example.com in one action.

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

Documentation on mod_rewrite for Apache 2.2.

If you've subdomains like forum.example.com, the first rule should be as is. Otherwise, you can do a negative match against www.example.com as well.

share|improve this answer
add comment

Doesn't the third line have to be:

RewriteCond %{HTTP_HOST} ^example\.com$
share|improve this answer
add comment

Try this:

RewriteCond %{REMOTE_ADDR} !127\.0\.0\.0
RewriteCond %{SERVER_PORT} 80 [OR]
RewriteCond %{HTTP_HOST} !^www.example\.com$
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.