Node.js www - non www redirection

前端 未结 6 1414
花落未央
花落未央 2020-12-13 00:14

Is there a chance to somehow redirect www to non-www URLs in node.js? Since there is no htaccess in node web server I am curious how to do that.

6条回答
  •  既然无缘
    2020-12-13 00:39

    An updated version of jmar777's answer:

    Using express

    server.use((req, res, next) => {
      if (req.headers.host.startsWith('www.')) {
          const newHost = req.headers.host.slice(4)
          return res.redirect(
            301,
            `${req.protocol}://${newHost}${req.originalUrl}`,
          )
      }
      next()
    })
    

提交回复
热议问题