I want to redirect all unmatched urls to my homepage. Ie. someone goes to www.mysite.com/blah/blah/blah/foo/bar or www.mysite.com/invalid_url - I want to redirect them to www.mysite.com
Obviously I don't want to interfere with my valid urls.
So is there some wildcard matcher that I can use to redirect requests to these invalid urls?
You can insert a 'catch all' middleware as last middleware/route in your Express chain:
//configure the order of operations for request handlers:
app.configure(function(){
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.static(__dirname+'/assets')); // try to serve static files
app.use(app.router); // try to match req with a route
app.use(redirectUnmatched); // redirect if nothing else sent a response
});
function redirectUnmatched(req, res) {
res.redirect("http://www.mysite.com/");
}
...
// your routes
app.get('/', function(req, res) { ... });
...
// start listening
app.listen(3000);
I use such a setup to generate a custom 404 Not Found page.
Add a route at the end of the rest of your routes.
app.all('*', function(req, res) {
res.redirect("http://www.mysite.com/");
});