6
votes

I need to redirect www and non www to https. I have looked everywhere on stackoverflow but can't find quite what I'm looking for.

The rules are:

  • example.com and www.example.com and https://example.com must redirect to https://www.example.com
  • It must match the domain and extension example.com. It cannot be a wild card which also matches abc.com or 123.com or example.net or anything else
  • It must match for www subdomains only. It cannot be a wild card which also matches sub.example.com or thisisademo.example.com

I currently have:

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

However if someone enters www.example.com it still goes to the http version instead of https.

What I think I actually need here is RewriteCond regex to match exactly and only "example.com" and "www.example.com"

Thanks

3

3 Answers

8
votes

You can use the following rule to redierct non-www or www to https://www in just one redirection

#redirect http non-www to https://www
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$
RewriteRule (.*) https://www.example.com/$1 [R=301,L]
#redirect https non-www to www
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule (.*) https://www.example.com/$1 [R=301,L]

Clear your browser's cache before testing this rule.

2
votes

This is the only way it works for me - with !on instead of off and with %{ENV:HTTPS} instead of %{HTTPS}:

  #non-www. http to www. https
  RewriteCond %{ENV:HTTPS} !on
  RewriteCond %{HTTP_HOST} ^(www\.)?yourdomain\.com$
  RewriteRule (.*) https://www.yourdomain.com/$1 [R=301,L]

  #non-www. https to www. https
  RewriteCond %{ENV:HTTPS} on
  RewriteCond %{HTTP_HOST} ^yourdomain\.com$
  RewriteRule (.*) https://www.yourdomain.com/$1 [R=301,L]
0
votes
#First rewrite any request to the wrong domain to use the correct one (i.e. www.)
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

#Now, rewrite to HTTPS:
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]