将httpredirect到https express.js

我试图重新路由http (80)https (443)在我的快递应用程序。 我正在使用一些中间件来做到这一点。 如果我去我的https://my-example-domain.com ,一切都很好。 但是,如果我去http://my-example-domain.com它不redirect,什么都没有显示。

我也在我的Ubuntu服务器上设置了一些iptables

 sudo iptables -A INPUT -i eth0 -p tcp --dport 80 -j ACCEPT sudo iptables -A INPUT -i eth0 -p tcp --dport 443 -j ACCEPT sudo iptables -A INPUT -i eth0 -p tcp --dport 8443 -j ACCEPT sudo iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 443 -j REDIRECT --to-port 8443 function requireHTTPS(req, res, next) { if (!req.secure) { return res.redirect('https://' + req.headers.host + req.url); } next(); } // all environments app.set('port', process.env.PORT || 8443); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(express.logger('dev')); app.use(requireHTTPS); // redirect to https app.use(express.json()); app.use(express.urlencoded()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); app.get('/', function(req, res){ res.render('index'); }) https.createServer(options, app).listen(8443); 

所以我的问题是我只需要添加另一个iptables规则? 或者我需要在我的应用程序中configuration一些东西?

所以基于下面的一个答案,我不认为它是一个中间件问题,而是一个端口问题。 例如:如果我去http://my-example-domain.com ,不起作用。 但是,如果我添加端口8443, http: //my-example-domain.com:8443,它redirect罚款。

 var redirectApp = express () , redirectServer = http.createServer(redirectApp); redirectApp.use(function requireHTTPS(req, res, next) { if (!req.secure) { return res.redirect('https://' + req.headers.host + req.url); } next(); }) redirectServer.listen(8080); 

您只需在您的快速应用程序中听取http和https。 然后包括中间件,如果不安全,则重新路由。 然后添加一个iptable重新路由443 => 8443。完成。

这应该工作。

 app.use(function(req,resp,next){ if (req.headers['x-forwarded-proto'] == 'http') { return resp.redirect(301, 'https://' + req.headers.host + '/'); } else { return next(); } }); 

我正在使用一个类似的解决scheme,在这里我也预先'www',因为我们的SSL证书没有它是无效的。 在每个浏览器中工作正常,但Firefox。 任何想法?

 http.createServer(function(req, res) { res.writeHead(301, { Location: "https://www." + req.headers["host"].replace("www.", "") + req.url }); res.end(); }).listen(80); 

您可以实现从http到https的redirect

 if(req.headers["x-forwarded-proto"] == "http") { res.redirect(301, "https://" + req.host+req.url); next(); }