Htaccess Redirect to HTTPS WWW domain

In this post I’ll show you how I did my configuration so that my WordPress redirects to https and www all my traffic. Redirect to https://www is done by placing a .htaccess file in your ‘html’ directory. Just create an empty text file and name it that way and place it in ht_docs or public_html/, www/ if you’re on a shared hosting.

This is if you want every time someone writes something like:

To redirect to:

Aka you want both https and www mandatory.

Redirect to https www htaccess file example

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

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

Let’s take it step by step. We have one case, http://www to https://www.

  • RewriteCond %{HTTPS} off – means when we write URL not with HTTPS but with HTTP (not secure, HTTPS off).
  • RewriteCond %{HTTP_HOST} ^(www\.)?yoursite\.com$
    • ^ means starts with.
    • everything inside (…) means should be processed as a group.
    • \. is just an escape character for ‘.‘ because we cannot write it directly in the .htaccess file.
    • ?yoursite means ‘yoursite’ text must be present zero or once.
    • \. again we escape the dot.
    • com must be present.
    • $ means string termination.
    • basically means when address starts with www followed by a (.) dot then your domain name then dot (.) then domain extension then it should redirect to what we write in rewrite rule.
  • RewriteRule (.*)$1 [R=301,L]
    • (.*) matches 0 or unlimited characters except line terminators, aka replace everything we previously written as the URL with
    • $1 contains all params possibly passed to the URL. will become
    • R=301 sends HTTP header 301 moved permanently as response, L = last, do not continue rewriting any more rules.

The second part of the htaccess file, https://domain to https://www redirect

  • RewriteCond %{HTTPS} on – obviously when we type https:// but omit www.
  • RewriteCond %{HTTP_HOST} ^$
    • ^ – url starts with
    • $ string termination. Basically it’s the same explanation as above.
  • RewriteRule (.*)$1 [R=301,L]
    • (.*) replace all of the original URL with
    • any params or paths are send as well through the $1 variable
    • send HTTP response 301 and L, means stop processing any other rewriting rules (Last)

You can learn more about regex here. Just copy and paste some expressions and see what you get.

You can read more about the .htaccess file and mod_rewrite at this official link.

Btw, if your .htaccess file already has RewriteEngine on just paste contents of redirect https www rules. You need only one RewriteEngine on directive per file.