We are currently creating a course on React. If you find anything difficult to understand in React, let us know about it so that we can try our level best to cover it in our course.
Just write to us at mail@codeguage.com.
Backend Development

Force www and https using htaccess

6 October 2018

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!

More to explore

Learning shouldn't stop at just one course!