NodeJS – 具有路由改变的反向代理

我正在使用NodeJS / Express作为在端口80上运行在我的VPS上的简单域路由器。我的routes.coffee看起来像这样:

request = require("request") module.exports = (app) -> #404, 503, error app.get "/404", (req, res, next) -> res.send "404. Sowway. :(" app.get "/error", (req, res, next) -> res.send "STOP SENDING ERRORS! It ain't cool, yo." #Domain Redirects app.all '/*', (req, res, next) -> hostname = req.headers.host.split(":")[0] #Website1.com if hostname == 'website1.com' res.status 301 res.redirect 'http://facebook.com/website1' #Example2.com else if hostname == 'example2.com' pathToGo = (req.url).replace('www.','').replace('http://example2.com','') request('http://localhost:8020'+pathToGo).pipe(res) #Other else res.redirect '/404' 

正如你可以在Example2.com中看到的,我试图将代理反向到另一个端口上的另一个节点实例。 总的来说,它完美的作品,除了一个问题。 如果其他节点实例上的路由发生更改(从example2.com/page1.htmlredirect到example2.com/post5) ,则地址栏中的URL不会更改。 会有人碰巧有一个很好的解决方法吗? 或者,也许更好的方法来反向代理? 谢谢!

为了redirect客户端,您应该将http-status-code设置为3xx并发送一个位置标题。

我不熟悉请求模块,但我相信它默认遵循redirect。 另一方面,您正在pipe理代理请求对客户端响应对象的响应,放弃标题和状态代码。 这就是客户不redirect的原因。

这是一个使用内置HTTP客户端的简单反向HTTP代理。 它是用JavaScript编写的,但是如果你愿意的话,你可以很容易地把它翻译成咖啡脚本和使用请求模块。

 var http = require('http'); var url = require('url'); var server = http.createServer(function (req, res) { parsedUrl = url.parse(req.url); var headersCopy = {}; // create a copy of request headers for (attr in req.headers) { if (!req.headers.hasOwnProperty(attr)) continue; headersCopy[attr] = req.headers[attr]; } // set request host header if (headersCopy.host) headersCopy.host = 'localhost:8020'; var options = { host: 'localhost:8020', method: req.method, path: parsedUrl.path, headers: headersCopy }; var clientRequest = http.request(options); clientRequest.on('response', function (clientResponse) { res.statusCode = clientResponse.statusCode; for (header in clientResponse.headers) { if (!clientResponse.headers.hasOwnProperty(header)) continue; res.setHeader(header, clientResponse.headers[header]); } clientResponse.pipe(res); }); req.pipe(clientRequest); }); server.listen(80); // drop root privileges server.on('listening', function () { process.setgid && process.setgid('nobody'); process.setuid && process.setuid('nobody'); });