Redirect to HTTPS

JavaScript, Browser · Oct 22, 2020

Redirects the page to HTTPS if it's currently in HTTP.

  • Use location.protocol to get the protocol currently being used.
  • If it's not HTTPS, use location.replace() to replace the existing page with the HTTPS version of the page.
  • Use location.href to get the full address, split it with String.prototype.split() and remove the protocol part of the URL.
  • Note that pressing the back button doesn't take it back to the HTTP page as its replaced in the history.
const httpsRedirect = () => {
  if (location.protocol !== 'https:')
    location.replace('https://' + location.href.split('//')[1]);
};
httpsRedirect();
// If you are on http://mydomain.com, you are redirected to https://mydomain.com

More like this

  • URLs in JavaScript

    Snippet collection

    Working with URLs is an essential skill for web developers. This snippet collection covers all the necessary resources to master URLs in JavaScript.

  • Scroll position

    JavaScript, Browser

    Returns the scroll position of the current page.

  • Current page protocol

    JavaScript, Browser

    Gets the protocol being used on the current page.

  • URL parameters as object

    JavaScript, Browser

    Creates an object containing the parameters of the current URL.