Files
30-seconds-of-code/snippets/httpsRedirect.md
Mathias Bynens 8ee50178f3 Avoid confusing prototype methods for static methods
Correct: `Array.from()` (it’s a static method)
Incorrect: `Array.join()` (doesn’t exist; it’s a prototype method)

This patch uses the common `#` syntax to denote `.prototype.`.
2018-09-28 15:44:12 -04:00

16 lines
729 B
Markdown

### httpsRedirect
Redirects the page to HTTPS if its currently in HTTP. Also, pressing the back button doesn't take it back to the HTTP page as its replaced in the history.
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.
```js
const httpsRedirect = () => {
if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]);
};
```
```js
httpsRedirect(); // If you are on http://mydomain.com, you are redirected to https://mydomain.com
```