Redirect all requests in ExpressJS except the main index page?
angularjs, express
Solution
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);
};
};
});
Problem
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); ```