Redirecting users from http to https on shared hosting — without .htaccess

Serving your website pages on https is a good thing — adding that extra layer of security. I recently had to help a friend redirect his website traffic from http to https. The website was running on a shared hosting plan with Media Temple.

There are usually two immediate solutions that come to mind.

Control panel support

Most hosting control panels have the option to redirect domains but not all have the option to redirect traffic from http to https for the same domain, as doing this wrongly could end up in redirect loops that can likely bring the server to a halt. In this case Media Temple admin panel didn’t have the option to redirect all traffic from http to https for the hosted domain.

.htaccess

It is possible to use a .htaccess file to achieve this. In fact that file is quite powerful if you know how to feed it with info it needs. A quick Google search gave us the entries we needed to add to the .htaccess file.

RewriteEngine On
RewriteCond %{HTTPS} !^on$
RewriteRule (.*) https://thespecificdomain.com/$1 [R,L]

This seemed to work sometimes and failed other times. Typing the domain in my browser redirected me to the https version of the site. Expected behavior. A few people we asked to try from different locations didn’t get redirected. Clicking on the domain from the company’s Facebook page didn’t redirect to https. We both knew the .htaccess file usually should just work flawlessly — well, it wasn’t.

This led me to the final solution. One that was sure not to fail.

JavaScript

In a file that’s included on all pages of the website, I added the script below and case closed. Still working like a charm.

( location.href.indexOf('https') == -1 ) ?
location.href = location.href.replace('http', 'https') +
( ( location.search != '' ) ? '?' + location.search : '' ) : '';

Hope this saves someone some headache.