Node.js www - 非www重定向 [英] Node.js www - non www redirection

查看:102
本文介绍了Node.js www - 非www重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有机会将www重定向到node.js中的非www URL?由于节点Web服务器中没有htaccess,我很好奇如何做到这一点。

解决方案

你正在使用express,对吗?如果是这样,您可以创建所有GET请求的路由处理程序,检查它们是否为wwwURL,并在适当的情况下重定向到相应的非www URL。

  app.get('/ *',function(req,res,next){
if(req.headers.host.match(/ ^ www /) !== null){
res.redirect('http://'+ req.headers.host.replace(/ ^ www\。/,'')+ req.url);
} else {
next();
}
})


Is there a chance to somehow redirect www to non-www URLs in node.js? Since there is no htaccess in node web server I am curious how to do that.

解决方案

You're using express, right? If so you can make a route handler that all GET requests go through, checks if they're to a 'www' URL, and redirects to the appropriate non-www URL if appropriate.

app.get('/*', function(req, res, next) {
  if (req.headers.host.match(/^www/) !== null ) {
    res.redirect('http://' + req.headers.host.replace(/^www\./, '') + req.url);
  } else {
    next();     
  }
})

这篇关于Node.js www - 非www重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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