小编典典

如何使用Express重定向所有不匹配的URL?

node.js

我想将所有不匹配的URL重定向到我的主页。就是
有人去www.mysite.com/blah/blah/blah/foo/barwww.mysite.com/invalid_url-我想将他们重定向到www.mysite.com

显然,我不想干扰我的有效网址。

那么,是否可以使用一些通配符匹配器将请求重定向到这些无效的url?


阅读 419

收藏
2020-07-07

共1个答案

小编典典

您可以在Express链中插入“全部捕获”中间件作为最后一个中间件/路由:

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

我使用这样的设置来生成自定义404 Not Found页面。

2020-07-07