Heroku中的端口路由将所有http路由到https [英] Port routing in Heroku to route all http to https

查看:134
本文介绍了Heroku中的端口路由将所有http路由到https的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Heroku托管的节点应用程序上,我想将所有HTTP通信重定向到HTTPS,而无需运行单独的应用程序服务器.

On a Heroku-hosted node app, I want to redirect all HTTP traffic to HTTPS without running a separate app server.

上一篇文章自动HTTPS连接/重定向node.js/express 建议设置iptables

A previous post Automatic HTTPS connection/redirect with node.js/express recommended setting up iptables

iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 443 -j REDIRECT --to-port 3000

我不是很熟练-但是有人知道如何在Heroku上执行此操作吗?目标是将http路由到https-以最有效的方式完成该任务.

I'm not very expert - but does anyone know how to do this on Heroku? The goal is route http to https - whatever accomplishes that in the most efficient way.

谢谢!

推荐答案

我在Express中检查https,并在必要时重定向:
(您在使用Express吗?)

I check https within Express and redirect if necessary:
(are you using Express?)

function requireSecure(req, res, next){
  if(!req.secure){
    var port = app.myConfig.httpsPort || 443;
    if(port != 443){
      res.redirect('https://'+req.host+':'+port+req.originalUrl);
      console.log('redirecting to https://'+req.host+':'+port+req.originalUrl);
    } else {
      res.redirect('https://'+req.host+req.originalUrl);
      console.log('redirecting to https://'+req.host+req.originalUrl);
    };   
  } else {
    next();
  };   
}

// place before any other route to ensure all requests https
app.all('*', requireSecure); 

// You can instead protect individual routes like this:
app.get('/account' 
, requireSecure
, function(req, res, next){
  res.send(200, 'This route is definitely secure!')
});

// I THINK (but haven't tested,) that you can also place this 
// function as middleware in Express's stack, above your router 
// (but possibly below the static files handler, if you don't need https for those)
app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view options', {layout:false});
  app.set('view engine', 'jade');
  app.use(requireSecure);
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

// Listen to both http and https protocols:
var http  = require('http');
var https = require('https');
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);

这篇关于Heroku中的端口路由将所有http路由到https的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆