URL redirection

URL redirection is arguably a MUST to have in your website's server configurations since it unifies URL addresses on the site and ensures, for SSL enabled connections, that it is loaded with https protocol. In some cases URL redirection can also be a guard against canonical issues in websites.

In this article we will look at how to force redirect URLs on a page to its www and https version in htaccess.

The code

The following code will force www and https on your site:

RewriteEngine On
RewriteCond %{HTTP_HOST} (?www)\.example.com [NC]
RewriteRule (.*) https://www.example.com/$1 [R=301]

RewriteCond %{HTTPS} off
RewriteRule (.*) https://www.example.com/$1 [R=301]

What we do over here is this:

  1. First of all we turn on the Apache's rewriting engine to make sure that our rewriting directives are applied.
  2. Secondly we check whether the hostname begins with www and if it doesn't we redirect to https://www.example.com/$1 where $1 is the backreference of the URL part after the slash following the hostname. If it does contain www then we move on to our next step.
  3. Next we check whether the URL contains https and if not then redirect to the same previous URL - https://www.example.com/$1. If it does contain https then we are all good and no redirection needs to be performed.

And now you have a solid URL structure in place making sure all your user bases circulate around the https and www version of your site!