How to Detect HTTP or HTTPS then Force Redirect to HTTPS in JavaScript

Tutorialsrack 16/05/2021 Jquery Javascript

In this article, you will learn how to detect HTTP or HTTPS then force a redirect to HTTPS in javascript. Before you start this article, first you know about HTTPS, HTTPS stands for Hypertext Transfer Protocol Secure. It is used for secure communication over a computer network and is widely used on the Internet. In HTTPS, the communication protocol is encrypted using Transport Layer Security (TLS) or, formerly, Secure Sockets Layer (SSL). The protocol is therefore also referred to as HTTP over TLS, or HTTP over SSL

HTTPS creates a secure, encrypted connection between the user’s browser and the server they're trying to access. Since it's an encrypted connection, it prevents malicious hackers from stealing data that are transmitted from the user’s browser to the server. Your site has an HTTPS also tells users that they will trust your site. If you've had a site in HTTP as well as a similar version in HTTPS, you'll automatically redirect the user to the HTTPS site.

To implement this redirect, we will use the window.location.protocol property to identify the protocol and then use the window.location.replace() method to redirect the browser. The window.location is a property of the Window object and it is often used for redirects. The window.location returns a Location object, which contains a number of useful properties and methods:

  • window.location.protocol is used to return the web protocol used (HTTP: or HTTPS:)
  • window.location.replace() is used to replace the current document with a new one.

Here is the code for redirecting from HTTP to HTTPS

Code - Redirecting from HTTP to HTTPS
if (window.location.protocol == "http:") {
    console.log("you are accessing us via " + "an insecure protocol (HTTP). " + "Redirecting you to HTTPS.");
    window.location.href = window.location.href.replace("http:", "https:");
} else if (window.location.protocol == "https:") {
    console.log("you are accessing us via" + " our secure HTTPS protocol.");

"you are accessing us via our secure HTTPS protocol."

It is not a good idea because you just temporarily redirect users to HTTPS and the browser doesn't save this redirect.

I hope this article will help you to understand how to detect HTTP or HTTPS then force a redirect to HTTPS in javascript.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!

Related Posts


Recent Posts