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

son*_*oom 22 node.js express

我想将所有不匹配的网址重定向到我的主页.IE浏览器.有人去www.mysite.com/blah/blah/blah/foo/barwww.mysite.com/invalid_url- 我想重定向他们www.mysite.com

显然我不想干涉我的有效网址.

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

Dan*_*iel 35

在其余路线的末尾添加路线.

app.all('*', function(req, res) {
  res.redirect("http://www.mysite.com/");
});
Run Code Online (Sandbox Code Playgroud)

  • 如果添加这样的路由,那么你想要在你的路由之后使用的任何中间件,例如`express.static`,将永远不会被调用,即使你在中间件声明之后包含`app.all`([gist] (https://gist.github.com/robertklep/5608473)).可能不是问题,但可能会令人困惑. (5认同)
  • 我不知道你可以使用"全部".好答案. (2认同)

rob*_*lep 20

您可以在Express链中插入一个'catch all'中间件作为最后的中间件/路由:

//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);
Run Code Online (Sandbox Code Playgroud)

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