[tutorial] How to force HTTPS!

I made a simple npm package for Glitch, it does what it tells.

URL: https://www.npmjs.com/package/always-https
Source Code: https://github.com/NezbednikSK/always-https

I am not including a demo, because you only need to add it to your Glitch project.
(only works with express & http)

Hey @NezbednikSK,

There is another way to force HTTPS without installing an NPM package:

function checkHttps(req, res, next){
  // protocol check, if http, redirect to https
    return next()
  } else {
    res.redirect('https://' + req.hostname + req.url);

app.all('*', checkHttps);

Place this code in your server.js!

1 Like

An even easier way could be:

if (location.protocol != 'https:')
 location.href = 'https:' + window.location.href.substring(window.location.protocol.length);

Just add this to the bottom of your HTML document using this:

if (location.protocol != 'https:')
 location.href = 'https:' + window.location.href.substring(window.location.protocol.length);

I know, i know.
But this also works with any content-type and also the http module.

Forcing https from client-side is deprecated, considering the connection has to be made to create a new connection. When a server redirects a client it is considered to be a redirect signal, which is safer because no information is shared between the client and the server (this is for keep-alive connections).

People who are naive of pages might have javascript disabled, and only allow it on certain paged. If this is the case, your redirect method will never apply to the website.

This will also never work if you are trying to work with an API, considering the client will never understand that you are trying to redirect them, the client is most likely to expected JSON, XML or YAML or any other storage syntax.


Thanks for the valueable information.
I will try to fix this.