2012-05-24 62 views
2

我對節點使用expressjs並同時運行https和http。node.js expressjs模式匹配不等於

我想要求/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/*的路線除外?

謝謝!

+0

在第二個重定向中,你不應該只將非'/ secure/*'請求重定向到'http://'嗎? –

回答

3

一個簡單的解決問題的方法是:

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

只做重定向如果網址不/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 
}); 

應該這樣做。

+0

非常好,謝謝! – dzm