Redirect the page to HTTPS if it is in HTTP

Replace an http: address with the same address over https:.

JavaScriptBrowser · DOM Version 1.0.0 · MIT · .md

redirect-the-page-to-https-if-it-is-in-http.js
function redirectToHttps() {
  if (location.protocol !== 'http:') return;
  const url = new URL(location.href);
  url.protocol = 'https:';
  location.replace(url);
}

Usage

usage.js
redirectToHttps(); // e.g. http://example.com/pricing → https://example.com/pricing

Reviewed, not executed: calling it navigates away from the page.

Know the limits

  • A client-side redirect runs after the insecure page has loaded. Redirect at the server or CDN with a 301, and send Strict-Transport-Security so browsers stop requesting HTTP.
  • location.replace keeps the HTTP address out of the history, so Back does not loop. A non-default port is kept.

The function above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.

Source & maintenance

Based on Redirect the page to HTTPS if it is in HTTP from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.

Builds the HTTPS URL with the URL API; server-side redirect and HSTS recommended. Reviewed, not executed, because it navigates. Original MDX retained as inert source evidence.

Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.

Reviewed, not executed: calling it navigates away from the page · reviewed October 28, 2026.

Keep exploring

Type two or more characters. Try “duplicate”, “webhook” or “retry”.