Sean Anderson
Sean Anderson

Reputation: 29301

Redirect http://www. and http:// to https for both root and subdomain

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?

Upvotes: 1

Views: 317

Answers (1)

anubhava
anubhava

Reputation: 785176

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

Upvotes: 2

Related Questions