URL Rewriting with ExpressJS

前端 未结 5 1353
灰色年华
灰色年华 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 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?

提交回复
热议问题