Hairgami_Master
Hairgami_Master

Reputation: 5539

Redirect all requests in ExpressJS except the main index page?

I'm hosting an ExpressJS/AngularJS site on Heroku, and I'm using Express to redirect all non-https requests to the https version.

My problem is- I don't want to redirect the Home page- everything else, yes. I want to just serve the home page without an https redirect. Any ideas how to do this with Express?

Many thanks!

app.get('*',function(req,res,next){
    if( req.headers['x-forwarded-proto'] != 'https' )
        res.redirect('https://mydomain.com'+req.url)
    else
        next() /* Continue to other routes if we're not redirecting */
})

app.use(express.static(__dirname));
app.listen(port);

Upvotes: 4

Views: 2068

Answers (2)

Plato
Plato

Reputation: 11062

app.all('*', function(req, res, next){
  if(req.path === '/'){
    next();
  } else if(req.secure){
    next();
  } else {
    var port = 443;  // or load from config
    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);
    };
  };
});

Upvotes: 5

Mr.Monshaw
Mr.Monshaw

Reputation: 450

if (process.env.DEVMODE == 'dev'){
    if( req.headers['x-forwarded-proto'] != 'https' )
        if !(req.url == homeURL)
           res.redirect('https://mydomain.com'+req.url)
    else
        next() /* Continue to other routes if we're not redirecting */
  } else {
        next();
  }
})

Upvotes: 0

Related Questions