我正在使用带有 Node 的 ExpressJS 并运行 https 和 http。
我想要求 /secure/*
的所有路由都使用 https。这样就完成了:
app.all("/secure/*", function(req, res, next) {
if (!req.connection.encrypted) {
res.redirect("https://" + req.headers["host"].replace(new RegExp(config.http_port, "g"), config.https_port) + req.url);
} else {
return next();
};
});
但是,我还想要求所有不使用 /secure/*
并尝试访问 https 的路由都使用相同的方法重定向到 http。
我尝试这样做:
app.all("*", function(req, res, next) {
console.log(req);
if (req.connection.encrypted) {
res.redirect("http://" + req.headers["host"].replace(new RegExp(config.https_port, "g"), config.http_port) + req.url);
} else {
return next();
};
});
但是在访问 https 页面时我最终陷入了重定向循环。有没有办法指定除 /secure/*
之外的所有路由?
谢谢!
最佳答案
解决您问题的一个简单方法是:
app.all("*", function(req, res, next) {
if (req.connection.encrypted && !/^\/secure/.test(req.url)) {
res.redirect("http://" + req.headers["host"].replace(new RegExp(config.https_port, "g"), config.http_port) + req.url);
} else {
return next();
};
});
仅当 URL 不以 /secure
开头时才执行重定向。
但是,我建议不要在 URL 中使用多余的“安全”标签,而只需将某些路径标记为 requireHTTP
或 requireHTTPS
。您知道您可以将多个方法传递到 app.get
和其他此类路由器方法中,对吧?假设您定义了 requireHTTP
和 requireHTTPS
(这与您的原始函数相同),您只需执行以下操作:
app.get("/path/to/keep/encrypted", requireHTTPS, function(req, res) {
// Rest of controller
});
app.get("/path/to/keep/public", requireHTTP, function(req, res) {
// Rest of controller
});
app.get("/path/you/dont/care/about/encryption/status", function(req, res) {
// Rest of controller
});
应该可以了。
关于Node.js ExpressJS 模式匹配不等于,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10744351/