【问题标题】:node.js expressjs pattern match not equalnode.js expressjs模式匹配不相等
【发布时间】:2012-05-31 10:36:38
【问题描述】:

我在 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/* 的路线?

谢谢!

【问题讨论】:

  • 在第二次重定向中,不应该只将非/secure/*的请求重定向到http://吗?

标签: node.js express


【解决方案1】:

解决问题的一个简单方法是:

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 中使用多余的“安全”标签,而是将某些路径标记为 requireHTTPrequireHTTPS。您知道您可以将多个方法传递给app.get 和其他此类路由器方法,对吧?假设您定义了 requireHTTPrequireHTTPS(与您的原始函数相同),您只需:

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
});

应该可以的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-07
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-22
    • 1970-01-01
    • 2019-03-31
    相关资源
    最近更新 更多