redirect non www and http – NodeJS and Express

Issue

I’m trying to redirect non-www urls to www within my Node JS / Express application.

The following snippet performs a 301 redirect successfully

function checkUrl(req, res, next) {
  let host = req.headers.host;
  if (host.match(/^www\..*/i)) {
    next();
  } else {
    res.redirect(301, "https://www." + host + req.url);
  }
}

I use it as so

app.all('*', checkUrl);

What it doesn’t cover is http to https. I can do this in a function of it’s own

function ensureSecure(req, res, next) {
  if (req.headers['x-forwarded-proto'] === 'https') {
    return next();
  }
  return res.redirect('https://' + req.hostname + req.url);
}

How can I combine the two so I can cover both scenarios

Solution

With express you can use app.use to run middleware on every request.

So combining what you’ve already achieved you get:

function checkUrl(req, res, next) {
  let host = req.headers.host;

  if (!host.match(/^www\..*/i))
  {
    return res.redirect(301, "https://www." + host + req.url);
  }
  else if (req.headers['x-forwarded-proto'] !== 'https')
  {
    return res.redirect('https://' + req.hostname + req.url);
  }
  next();
}

app.use(checkUrl);

Answered By – Joey Ciechanowicz

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published