如何使用Express重定向所有不匹配的URL? [英] How do I redirect all unmatched urls with Express?

查看:139
本文介绍了如何使用Express重定向所有不匹配的URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to redirect all unmatched urls to my homepage. Ie. someone goes to www.mysite.com/blah/blah/blah/foo/bar or www.mysite.com/invalid_url - I want to redirect them to www.mysite.com

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

Obviously I don't want to interfere with my valid urls.

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

So is there some wildcard matcher that I can use to redirect requests to these invalid urls?

推荐答案

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

You can insert a 'catch all' middleware as last middleware/route in your Express chain:

//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页面.

I use such a setup to generate a custom 404 Not Found page.

这篇关于如何使用Express重定向所有不匹配的URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆