how to redirect www and non www to https for specific domain using htaccess

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.


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]