如何使用Expressredirect所有不匹配的url?

我想将所有不匹配的urlredirect到我的主页。 IE浏览器。 有人去www.mysite.com/blah/blah/blah/foo/barwww.mysite.com/invalid_url – 我想redirect到www.mysite.com

显然我不想干涉我有效的url。

那么是否有一些通配符匹配器可以用来将请求redirect到这些无效的url?

你可以在你的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页面。

在其他路线的末尾添加路线。

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