HTTPS redirection only works when page is reloaded HTTPS redirection only works when page is reloaded express express

HTTPS redirection only works when page is reloaded


I think your server is sending the content before sending the redirection headers.

If you swap:

app.use(serveStatic(__dirname));app.use(forceSsl);

for:

app.use(forceSsl);app.use(serveStatic(__dirname));

It seems to work much better!

The reason why your browser did perform the redirection on reload/enter is obscure to me as I could not reproduce the behavior. On FF I was never redirected.

It might be due to the request headers being different, such as a HEAD, instead of a GET, or something else. I could not investigate more on that, use Wireshark or Burpsuite to know exactly what happens, if that still matters...


This redirectToHTTPS() middleware should work for you. It will redirect to https site even when the user does not provide prefix. Add X-Forwarded-Port for identifying the port used for https site.

function redirectToHTTPS () {  return function middlewareRedirectToHTTPS (req, res, next) {    const isNotSecure = (!req.get('x-forwarded-port') && req.protocol !== 'https') ||      parseInt(req.get('x-forwarded-port'), 10) !== 443    if (isNotSecure) {      return res.redirect('https://' + req.get('host') + req.url)    }    next()}}