1

I have the following rules in my .htaccess:

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

This causes domains such as http://www.domain.com to be redirected to https://domain.com as well as http://www.sub.domain.com to be redirected to https://sub.domain.com.

I would like to expand this rule to include redirection from http://domain.com to https://domain.com and http://sub.domain.com to https://sub.domain.com.

I've found a couple of examples online, but they don't seem to do quite what I would like:

I know this isn't a difficult change, but PHP/.htaccess files aren't my strongest suite. Could someone enlighten me?

Community
  • 1
  • 1
Sean Anderson
  • 27,963
  • 30
  • 126
  • 237

1 Answers1

2

Here is a rule that lets you do both redirects in one single rule:

RewriteCond %{HTTP_HOST}::%{HTTPS} ^(?:www\.(.+?)::o(?:ff|n)|(?!www\.)(.+?)::off)$ [NC]
RewriteRule ^ https://%1%2%{REQUEST_URI} [R=302,L,NE]

It will do following redirections:

  1. http://domain.com => https://domain.com
  2. http://www.domain.com => https://domain.com
  3. https://www.domain.com => https://domain.com
  4. http://www.sub.domain.com => https://sub.domain.com
anubhava
  • 761,203
  • 64
  • 569
  • 643