Back-End 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} (?www)\ [NC]
RewriteRule (.*)$1 [R=301]

RewriteCond %{HTTPS} off
RewriteRule (.*)$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$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 -$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!

More Courses

Learning shouldn't stop at just one course!


Make your web pages interactive and dynamic

Enroll »

Reload content without reloading the whole page

Enroll »

Give your web page the look you want

Enroll »
JavaScript RegExp

Matching patterns within strings in JavaScript

Enroll »
Advanced JavaScript

The real-pro aspects of JavaScript

Enroll »

Divide content into different slides

Enroll »
Lazy Loading

Learn to load images when the need be

Enroll »

Make searching more efficient

Enroll »

A simple and powerful programming language

Enroll »
Elementary Logic

The science of reasoning

Enroll »