How To Force www and https Using htaccess

Stay updated with our latest articles:

Table of Contents

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} ^example.com [NC]
RewriteRule (.*) https://www.example.com/$1 [R=301,L]

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

What we do over here is this:

  1. First of all, we turn on the Apache's rewriting engine, via RewriteEngine on to make sure that our rewriting directives are applied.
  2. Secondly, we check whether the hostname begins without www. If it does begin without www, then the rewrite condition in line 2 is met and thus a redirect response is sent back that points to the www version of the URL. The L flag effectively signals this rewrite rule as the last rule and thus ends the rewriting.
  3. If the hostname does begin with www, then we have another check to perform — that of https. If the URL does not contain https, we send a redirect request for the URL with https. Once again, the L flag ends any further rewriting for the current phase.

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!

Never miss an article

Follow Codeguage on either of the following channels and stay updated with every latest blog article that we publish.

Improve your web development knowledge, today!