gpt4 book ai didi

node.js - Heroku中的端口路由将所有http路由到https

转载 作者:太空宇宙 更新时间:2023-11-03 13:18:19 25 4
gpt4 key购买 nike

在 Heroku 托管的 Node 应用程序上,我想将所有 HTTP 流量重定向到 HTTPS 而无需运行单独的应用程序服务器。

以前的帖子 Automatic HTTPS connection/redirect with node.js/express建议设置 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 - 以最有效的方式实现这一点。

谢谢!

最佳答案

我在 Express 中检查 https 并在必要时重定向:
(您在使用 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);

关于node.js - Heroku中的端口路由将所有http路由到https,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17709862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com