URL Rewriting with ExpressJS

You could rewrite the URL before you get to the handler you want to use.

app.use(function(req, res, next) {
   if (req.url === '/toto') {
     req.url = '/heytoto';
   }
   next();
});

app.get('/heytoto', ...);

I've used a similar method to do URL rewrites with regular expressions.


So I had sort of the same issue. I wrote an app that uses the history API on browsers and I wanted to rewrite all non-static URLs back to index.html. So for static files I did:

app.configure(function() {
  app.use('/', express.static(__dirname + '/'));
});

But then for the history API generated paths I did:

app.get('*', function(request, response, next) {
  response.sendfile(__dirname + '/index.html');
});

This meant that any request that wasn't a file or directory in / (such as a URL generated by the history API) wouldn't be rewritten or redirected but instead the index.html file will be served and that then does all the JS routing magic.

Hopefully that's close to what you're looking for?