HTTP to HTTPS 301 Redirection

Tara Prasad Swain HTML5, JavaScript, PHP, SEO

In this article I am going to explain how to redirect your website from HTTP to HTTPS using different redirection methods with 301 status code.

To know more about the 301 status code and its importance please check my previous article When to use 404, 301 and 302 HTTP status code

Best method is using HTACCESS

Put below code in your .htaccess file


<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,NC,L]
</IfModule>

Using Meta Refresh, this redirection is not 301 but Google considers this as 301 redirect.
Please use below code.


<html>
<head>
   <meta http-equiv="refresh"
   content="0; url=https://www.yourdomain.com/">
</head>
<body>
   <p>The page has moved to:
   <a href="https://www.yourdomain.com/">this page</a></p>
</body>
</html>

Using JavaScript redirection

Since 301 status redirection is server side, JavaScript has restrictions.

Please use below code.


if (window.location.protocol !== 'https:') {
    window.location.href = 'https://' + window.location.hostname + window.location.pathname + window.location.hash;
}

Hope this helps.

Share this Post