Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect http to https express.js

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.

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

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

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.

like image 652
Jackson Geller Avatar asked Dec 20 '22 17:12

Jackson Geller


1 Answers

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);
like image 69
pykiss Avatar answered Dec 26 '22 01:12

pykiss