node.js expressjs模式匹配不相等
我使用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,都使用相同的方法redirect到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页面时,我最终处于redirect循环。 有没有办法指定所有的路线,除了那些/secure/*
?
谢谢!
你的问题的一个简单的解决scheme是:
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
开头时才执行redirect。
不过,我build议不要在URL中使用冗余的“安全”标签,只要将某些path标记为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 });
这应该做到这一点。