Detect HTTP or HTTPS then force HTTPS in JavaScript

It is not good idea because you just temporary redirect user to https and browser doesn't save this redirect.

You describe task for web-server (apache, nginx etc) http 301, http 302


Try this

if (location.protocol !== 'https:') {
    location.replace(`https:${location.href.substring(location.protocol.length)}`);
}

location.href = blah adds this redirect to the browser history. If the user hits the back button, they will be redirected back to the the same page. It is better to use location.replace as it doesn't add this redirect to the browser history.


Setting location.protocol navigates to a new URL. No need to parse/slice anything.

if (location.protocol !== "https:") {
  location.protocol = "https:";
}

Firefox 49 has a bug where https works but https: does not. Said to be fixed in Firefox 54.