【发布时间】: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.com和https://www.example.com工作,但问题的第二部分仍未解决。https://www.example.com不会重定向到https://example.com和 @ 987654330@ 不会重定向到https://example.com。我理解这一点的方式是,我需要做的就是正确设置重定向,并且不需要通配符证书。 -
好的,我对请求做了一些调试。重定向不起作用,因为即使用户访问
https://www.example.com、req.host===example.comNOTwww.example.com。这是否意味着 NS 记录仍有问题? -
req.host 是当前请求 URL 的一部分,表示主机名。这里不涉及NS。
https://test.example.com主机将是test.example.com
标签: node.js redirect express server