Redirect the page to HTTPS if it is in HTTP
Replace an http: address with the same address over https:.
function redirectToHttps() {
if (location.protocol !== 'http:') return;
const url = new URL(location.href);
url.protocol = 'https:';
location.replace(url);
}
Usage
redirectToHttps(); // e.g. http://example.com/pricing → https://example.com/pricing
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.
Keep exploring
- Convert Celsius to Fahrenheit — Apply the temperature conversion without rounding the result.
- Convert hex to RGB — Expand #rgb if needed and read the red, green and blue channels.
- Convert URL parameters to object — Read a query string into an object; repeated keys become arrays.