如何通过快递中的https检查请求是否已经过来

时间:2011-11-16 13:46:00

标签: node.js express

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

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

3 个答案:

答案 0 :(得分:12)

我也部署在Heroku上。当他们使用nginx反向代理时,他们会添加一堆标题。对这种情况感兴趣的是x-forwarded-proto。

这就是我所做的:

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

答案 1 :(得分:1)

app.enable(' trust proxy');

"在Varnish或Nginx等反向代理后面使用Express是微不足道的,但它确实需要配置。通过启用"信任代理"通过app.enable设置('信任代理'),Express会知道它位于代理后面,并且X-Forwarded- *标题字段可能是可信的,否则可能很容易。欺骗"

Express behind proxies doco

答案 2 :(得分:0)

为了运行安全服务器(https),必须独立于非安全服务器(http)创建它。他们还会在不同的端口上收听。尝试这样的事情:

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_secure()。