将 http 重定向到 https express.js [英] Redirect http to https express.js

查看:24
本文介绍了将 http 重定向到 https express.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的 express 应用中将 http (80) 重新路由到 https (443).我正在使用一些中间件来做到这一点.如果我去我的 https://my-example-domain.com,一切都很好.但是,如果我转到 http://my-example-domain.com,它不会重定向,也不会显示任何内容.

I'm trying to reroute http (80) to https (443) in my express app. I'm using some middle ware to do this. If i go to my https://my-example-domain.com, everything is fine. But if I go to http://my-example-domain.com it does not redirect and nothing shows up.

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

I also have setup some iptables on my ubuntu server

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 规则?还是我需要在我的应用中配置一些东西?

So my question is do I just need to add another iptables rule? Or do I need to configure something in my app?

因此,根据下面的一个答案,我认为这不是中间件问题,而是端口问题.例如:如果我转到 http://my-example-domain.com,则不起作用.但是如果我添加端口 8443,http://my-example-domain.com:8443,它重定向正常.

So based on one answer below, I don't think its a middleware problem, but a port issue. For example: if i go to http://my-example-domain.com, doesn't work. But if I add port 8443,http://my-example-domain.com:8443, it redirects fine.

推荐答案

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 express.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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