# Redirect the page to HTTPS if it is in HTTP

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

Canonical: https://1loc.dev/misc/redirect-the-page-to-https-if-it-is-in-http/
Version: 1.0.0
Runtime: JavaScript · modern browsers (DOM)
Verification: Reviewed, not executed: calling it navigates away from the page
Updated: 2026-10-28

## Implementation

```javascript
function redirectToHttps() {
  if (location.protocol !== 'http:') return;
  const url = new URL(location.href);
  url.protocol = 'https:';
  location.replace(url);
}
```

## Usage

```javascript
redirectToHttps(); // e.g. http://example.com/pricing → https://example.com/pricing
```

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

## 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 does not validate its arguments. Add checks where it receives untrusted input.

## Source and license

Original: https://github.com/phuocng/1loc/blob/14b481cf60dff1620ab1bb99a43b1f68068cdd9b/contents/redirect-the-page-to-https-if-it-is-in-http.mdx
Author: Nguyen Huu Phuoc and original contributors
Contributors: See original repository history
Source commit: 14b481cf60dff1620ab1bb99a43b1f68068cdd9b
Copyright (c) 2020 phuoc-ng
License: MIT — https://1loc.dev/licenses/
Maintainer: Oveyon
Modifications: 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.
