Open In App

How to detect HTTP or HTTPS then force redirect to HTTPS in JavaScript ?

HTTPS stands for Hypertext Transfer Protocol Secure. As its name implies, it creates a secure, encrypted connection between the user’s browser and the server they are trying to access. Since it is an encrypted connection, it prevents malicious hackers from stealing data that is transmitted from the user’s browser to the server. Having a site in HTTPS also tells users that they can trust your site. If you have a site in HTTP as well as the same version in HTTPS, you can automatically redirect the user to the HTTPS site.
To implement this redirect, we will use JavaScript code. Specifically, we will use the window.location.protocol property to identify the protocol and then use window.location.href property to redirect the browser. The window.location is a property of the Window object. It is often used for redirects. The window.location returns a Location object, which contains a number of useful properties: 

Note: Since window.location.href is writable, we will set a new URL to it and therefore reload the browser with the new URL.



Example: 




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
    (window.location.protocol == "https:") {
        console.log("you are accessing us via"
            + " our secure HTTPS protocol.");
    }

Output:  



// On HTTP sites, you will be redirected to the HTTPS version.

Disadvantages: There are some downsides to setting an HTTPS redirect from the browser side. These downsides include: 

Therefore, we recommend redirecting users via HTTPS on the server-side instead of in JavaScript. We have added an example below on how to do this redirect using NodeJS, which is a server written in Javascript. Using NodeJS on the server, the code is similar but not exactly the same. We will use req.protocol instead. 

Example (app.js):




app.get('/', function(req, res, next) {
    if (req.protocol == 'http') {
        res.redirect('https://' +
        req.get('host') + req.originalUrl);
    }
});

Output:  

// On HTTP sites, you will be redirected to the HTTPS version.

Note: The req.protocol does not include the colon (eg: http or https) whereas window.location.protocol does (eg: http: and https:).


Article Tags :