URL Rewriting with ExpressJS

前端 未结 5 1330
灰色年华
灰色年华 2020-12-05 04:37

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

相关标签:
5条回答
  • 2020-12-05 04:58

    Try this:

    app.get('/toto', function(req, res) {
      res.redirect('/heytoto');
    });
    
    0 讨论(0)
  • 2020-12-05 05:01

    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?

    0 讨论(0)
  • 2020-12-05 05:02

    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.

    0 讨论(0)
  • 2020-12-05 05:17

    you could check the url with an if condition and use app.redirect to redirect to a certain url.

    0 讨论(0)
  • 2020-12-05 05:23

    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.

    0 讨论(0)
提交回复
热议问题