ramazan793
ramazan793

Reputation: 689

Node js - How to get url name?

I tried to redirect from www to non-www, but couldn't. Look at my code:

function wwwRedirect(req, res, next) {
  console.log('Got url ' + req.headers.host)  // return example.com (without 'www'), even if I go to www.example.com
  console.log('req.get("host") ' + req.get('host')) // same
  if (req.headers.host.slice(0, 4) === 'www.') { // not working, cause req.headers.host doesn't contain 'www', even if Im connecting to www.example.com
      var newHost = req.headers.host.slice(4);
      return res.redirect(301, req.protocol + '://' + newHost + req.originalUrl);
      console.log('New url ' + req.protocol + '://' + newHost + req.originalUrl)
  }
  next();
};

app.set('trust proxy', true);
app.use(wwwRedirect);

Please, look at all comments above. So, I can't make redirection. What am I doing wrong? Why req.headers.host doesn't contain 'www.' even if I connect with 'www.example.com'

Upvotes: 0

Views: 207

Answers (1)

Masoud
Masoud

Reputation: 1064

You can do something like this:

app.use(function(req, res, next) {
  if (req.headers.host.match(/^www/) !== null ) {
    res.redirect('http://' + req.headers.host.replace(/^www\./, '') + req.url);
  } else {
    next();     
  }
})

Upvotes: 1

Related Questions