重定向非 www 和 http - NodeJS 和 Express

Ric*_*wis 1 node.js express

我正在尝试在 Node JS / Express 应用程序中将非 www 网址重定向到 www。

以下代码片段成功执行 301 重定向

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

我这样使用它

app.all('*', checkUrl);
Run Code Online (Sandbox Code Playgroud)

它没有涵盖的httphttps. 我可以用它自己的函数来做到这一点

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

我如何将两者结合起来,以便我可以涵盖这两种情况

Joe*_*icz 5

使用express,您可以app.use根据每个请求运行中间件。

因此,结合您已经取得的成就,您将得到:

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);
Run Code Online (Sandbox Code Playgroud)