[Solved] Auto redirect http -> https

Glitch apps respond to both http and https protocols.

Is there a setting or something to force https?

I adapted a StackOverflow answer into some Node/Express middleware:

function ensureSecure(req, res, next) {

    if (req.headers["x-forwarded-proto"].match(/https/g)) {
        return next();
    }

    res.redirect(302, `https://${req.hostname}${req.url}`);
}

I initially had the thought to use the ‘global’ regex because Glitch’s “x-forwarded-proto” header repeats the protocol 5 times :smiley:

'x-forwarded-proto': 'https,http,http,http,http'

But then I noticed that regardless of whether I connect via http or https, the request gets the same “x-forwarded-proto” header value! So my conditional is useless.

I don’t know enough to phrase this correctly, but I’m guessing the forced https setting will have to be set in .htaccess or config file somewhere.

1 Like

There’s no setting, we leave it to project authors to implement. We used to force http to https, but that was problematic for some use-cases. The following project example works: https://glitch.com/edit/#!/large-patch it’s very similar to your approach, but correctly identities http requests.

4 Likes

Thanks @Gareth,

After reviewing your linked project, and re-reviewing my proposed middleware above, I realized that I was not looking closely at the request headers I was logging.

I incorrectly stated that the headers were the same regardless of access via http or https:

'x-forwarded-proto': 'https,http,http,http,http'

In reality, if I connect using plain http that header is:

'x-forwarded-proto': 'http,http,http,http,http'

The headers are different; I just missed the difference. Your demo using indexOf achieves the same goal as my regex, which got me wondering why yours worked and mine didn’t. Which got me to take another look at the headers as I logged them.

1 Like

Sorry for the necrobump, but how does this policy apply to basic web page projects (not node ones)? If forced HTTPS causes problems for some projects, then having a choice for those kinds of projects would be very useful!

You could do something like:

<script>
if (location.protocol != 'https:') {
 location.href = 'https:' + window.location.href.substring(window.location.protocol.length);
}
</script>
3 Likes

Sorry for replying such an old topic, but the above solution for basic web page projects (client side sctipt) don’t satisfy the Autit tab (Lighthouse) on the Dev Tools of Chrome, as you can check on my project https://andre-baptista.glitch.me/.

Any idea?

Thanks

+1 to albs-br’s comment, a server redirect would be needed to satisfy Lighthouse’s audit. Enabling this functionality would be great. Thanks

1 Like