我如何检查一个请求是通过https快速发送的

我希望强制某些路线在我的快车应用程序中始终使用安全连接。 我如何检查以确保它使用https?

我在heroku上使用piggyback ssl进行部署。

我也部署在Heroku上。 当他们使用nginx来反向代理时,他们添加了一堆他们的头文件。 在这种情况下的兴趣之一是x前锋原。

这就是我所做的:

app.get(/\/register$/, function(req, res){ console.log(JSON.stringify(req.headers)); //to see all headers that heroku adds if(req.headers['x-forwarded-proto'] && req.headers['x-forwarded-proto'] === "http") { res.redirect("https://" + req.headers.host + req.url); } else { //the rest of your logic to handle this route } }); 

app.enable('信任代理');

“在反向代理(如Varnish或Nginx)后面使用Express是微不足道的,但它确实需要configuration。通过通过app.enable('trust proxy')启用”trust proxy“设置,Express将知道它位于代理而X-Forwarded- *头域可能是可信的,否则可能很容易被欺骗。

表示在代理doco后面

为了运行一个安全的服务器(https),它必须独立于不安全的服务器(http)创build。 他们也会听取不同的端口。 尝试这样的事情:

 var express = require('express) , app_insecure = express.createServer() , app_secure = express.createServer({ key: 'mysecurekey' }) app_insecure.get('/secure-page',function(req, res){ // This is an insecure page, redirect to secure res.redirect('https://www.mysecuresite.com/secure-page') }) app_secure.get('/secure-page', function(req,res){ // Now we're on a secure page }) app_insecure.listen(80) app_secure.listen(443) 

或者这可以被实现为路由中间件

 var redirect_secure = function(req, res, next){ res.redirect('https://mysite.com' + req.url) } app_insecure.get('/secure-page',redirect_secure,function(req, res){}) 

现在,您只需要在要redirect到安全位置的path上包含函数reference:redirect_secure()。