How do I redirect all unmatched urls with Express?

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/");
});

I'm super early here but this is my solution to this

app.get('/', (req, res) => {
    res.render('index')
})

app.get('*', (req, res) => {
    res.redirect('/')
})

Just uses the order of routes to redirect 1 specific url before it has a catch-all route for everything else. You can put whatever route you want to have above the catch-all and you'll be good to go.

My example just redirects and url given to the same root page