Node Express:使用代理时res.redirect中断

我使用Apache ProxyPass(在httpd.conf中configuration),在代理后面运行节点快速应用程序:

ProxyPass /nodeapp http://localhost:9009 

我的应用程序使用Passport来authentication用户,所以当我访问基本path时,我应该被redirect到login页面:

– 旧的redirect: http : //example.com : 9009 – > http://example.com:9009/login

– 新的redirect: http : //example.com/nodeapp – > http://example.com/nodeapp/login

不幸的是,redirect不起作用:

– redirect中断: http : //example.com/nodeapp – > http://example.com/login

我试图启用快速代理configuration,但这没有什么区别:

  app.enable('trust proxy'); 

**编辑:** Ethan在下面的评论中build议,我可以硬编码我所有的path,以适应新的环境,然而这将打破当我的本地计算机上运行的path('/')。

我正在寻找一个更集中的解决scheme,如果可能的话,可以适应不同的运行环境

为了同时工作,您需要计算每个请求的代理path或本地path。

我正在使用Nginx代理,它注入“x-forwarded-for”和“x-forwarded-proto”(oringinal请求的协议)。 转储“req.headers”以查看您的代理可能传递的标头。

在路由之前在你的Expressconfiguration文件中创build它:

 app.use(function(req, res, next) { if (req.headers.hasOwnProperty('x-forwarded-for')) { // proxy in effect req.redirUrl = req.headers['x-forwarded-proto'] + "://" + req.headers.host // proxy // plus any proxy subdirs if needed + "/" + proxy_subdir ; } else { // direct requeset req.redirUrl = req.protocol + "://" + req.headers.host ; } next(); }); 

你现在有一个req.redirUrl你可以在任何redirect的开始使用,这将在代理或直接访问的工作:

 res.redirect(req.redirUrl + "/redir_path");