【问题标题】:Node Express Server doesn't handle http redirects properlyNode Express 服务器无法正确处理 http 重定向
【发布时间】:2016-01-12 19:39:30
【问题描述】:

我正在尝试使用 2 个 Express 服务器的组合将用户从 http 重定向到 https,并将带有 www 的请求重定向到非 www,因为 cert 需要非 www。第一个问题,用户访问https://www.example.com 他们得到ERR_CONNECTION_REFUSED。第二个问题,用户访问http://www.example.com出现DNS错误。用户只能成功访问http://example.com(并被重定向)和https://example.com。我尝试了一些解决方案,但 Express 的许多示例似乎已经过时,需要更改哪些内容才能涵盖上述两个用例?

  // Create Express Server
  server = express();
  httpServer = express();

  // Redirect http to https
  httpServer.set('port', 80);

  httpServer.get("*", function (req, res, next) {
      res.redirect("https://" + req.headers.host + "/" + req.path);
  });

  http.createServer(httpServer).listen(80);


  server.set('trust proxy', true);

  // Add server static middleware
  server.use( st(options.prod.st) );

  server.use(function (req, res, next) {
    var str = "www.";
    if (req.headers.host.indexOf(str) === 0) {
      res.redirect(301, req.protocol + "://" + req.headers.host.slice(str.length) + req.originalUrl);
    } else {
      next();
    }
  });

  // Fallback to /index.html
  server.use(fallback(prodRoot));

  // Start Server
  https.createServer(creds, server).listen(options.prod.port);

【问题讨论】:

  • 默认 https 端口是 433,所以你需要监听它。要为 www.example.com 提供服务,您应该创建额外的 ns 记录。如果您需要从 https://www.example.com 重定向,则需要通配符证书。
  • options.prod.port = 443。我将查看通配符证书和 ns 记录。 TY
  • 好的,添加了 www ns 记录,现在 DNS 正在为 http://www.example.comhttps://www.example.com 工作,但问题的第二部分仍未解决。https://www.example.com 不会重定向到 https://example.com 和 @ 987654330@ 不会重定向到https://example.com。我理解这一点的方式是,我需要做的就是正确设置重定向,并且不需要通配符证书。
  • 好的,我对请求做了一些调试。重定向不起作用,因为即使用户访问https://www.example.comreq.host === example.com NOT www.example.com。这是否意味着 NS 记录仍有问题?
  • req.host 是当前请求 URL 的一部分,表示主机名。这里不涉及NS。 https://test.example.com 主机将是 test.example.com

标签: node.js redirect express server


【解决方案1】:

为 www 添加 NS 记录后,大多数问题都已解决。感谢@Fella 的建议。更正的代码如下。如果用户登陆https://www.example.com,我最终还必须解决一个问题,我需要添加一个 CORS 策略以防止在 Web 应用程序中的某些 XMLHttpRequests 上出现混合内容警告。我还删除了从 www 到非 www 的重定向,在修复 NS 记录后就没有必要了。

 // Create Connect Server
  server = express();
  httpServer = express();

  // Redirect http to https

  httpServer.get('*', function (req, res, next) {
      res.redirect(301, 'https://' + req.headers.host + req.path);
  });

  http.createServer(httpServer).listen(80);

  // Add serve static middleware
  server.use( st(options.prod.st) );

  // Implement CORS policy
  server.use(function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    next();
  });

  // Fallback to /index.html
  server.use(fallback(prodRoot));

  // Start Server
  https.createServer(creds, server).listen(443);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-09
    • 1970-01-01
    • 2020-09-20
    • 2017-03-07
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多