0

In NodeJS + Express, how to automatically remove URL 'www'? for example, client connect to https://www.stackoverflow.com then, https://stackoverflow.com connected! how to automatically remove URL 'www'?

이두종
  • 3
  • 1

1 Answers1

0

You may try below middleware right somewhere in beginning.

var wwwRedirect = function(req, res, next){
    if(req.get('host').indexOf('www.') === 0){
      if(req.method === "GET" && !req.xhr){
        return res.redirect(req.protocol + '://' + req.get('host').substring(4) + req.originalUrl);
      }
    }
  }
  next();
};

app.use(wwwRedirect);
ow3n
  • 5,974
  • 4
  • 53
  • 51
codeofnode
  • 18,169
  • 29
  • 85
  • 142