How to redirect www and non www to https for a specific domain using htaccess

I need to redirect www and non www to https. I looked everywhere in stackoverflow, but cannot find what I am looking for.

Rules:

  • example.com and www.example.com and https://example.com should be redirected to https://www.example.com
  • It must match the domain and extension example.com. It cannot be a wild card that also matches abc.com or 123.com or example.net or anything else
  • Compliance should only be for www subdomains. It cannot be a wild card that 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 logs on to www.example.com, they still switch to the http version instead of https.

I think what I really need is a RewriteCond regular expression to match exactly and only "example.com" and "www.example.com"

thank

+6
source share
3 answers

You can use the following rule for redierct non-www or www for https: // www in only one redirect

#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 cache before testing this rule.

+7
source

This is the only way for me: !oninstead offand %{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]
+2
#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]
0

All Articles