I would like to rewrite my URLs on my ExpressJS website. I\'ve used this plugin, https://github.com/joehewitt/express-rewrite, but it doesn\'t work...
However, I mig
Try this:
app.get('/toto', function(req, res) {
res.redirect('/heytoto');
});
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?
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.
you could check the url with an if condition and use app.redirect to redirect to a certain url.
A solution that works without response.sendfile(..)
is to use a rewrite middleware that is inserted prior to app.use(express.static(..))
like this:
// forward all requests to /s/* to /index.html
app.use(function(req, res, next) {
if (/\/s\/[^\/]+/.test(req.url)) {
req.url = '/index.html';
}
next();
});
// insert express.static(...)
This way, expressjs properly recognizes the rewrite. The static
middleware will then take care of serving the file.