【问题标题】:In NodeJS + Express, how to automatically remove URL 'www'?在 NodeJS + Express 中,如何自动删除 URL 'www'?
【发布时间】:2026-02-12 02:30:02
【问题描述】:

在 NodeJS + Express 中,如何自动删除 URL 'www'? 例如, 客户端连接到https://www.*.com 然后,https://*.com 连接! 如何自动删除 URL 'www'?

【问题讨论】:

标签: javascript node.js express url dns


【解决方案1】:

你可以在开始的地方尝试下面的中间件。

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);

【讨论】: