node.jsでリバースプロキシを構築する

node-http-proxyモジュールを使ってプロキシサーバーを構築してみる。

少し古い情報だと振り分け設定もできるようだったんだけど、現状GitHubに上がっているソースを見る限りそんな設定はなさそう。

どうなったかと思ってたら、下記に情報がありました。

基本的には下記のように自分で振り分けを書くみたい。

ちょっとめんどくさい気もするけど、正規表現での振り分けとか好きに作れる分、カスタマイズはしやすいかな。どんな実装がいいか引き続き考えてみよ。

※事前に npm install --save http-proxy でインストールしておく


var http = require('http'),

httpProxy =('http-proxy');

var proxy = httpProxy.createProxyServer();

var proxyTable = {

 "/path1/": "http://localhost:8080/",

 "/path2/": "http://localhost:8081/",

};

http.createServer(function (req, res) {

 setTimeout(function () {

  for (path in proxyTable) {

   if (req.url.lastIndexOf(path, 0) === 0) {

    proxy.web(req, res, {

     target: proxyTable[path]

    });

   break;

  }

 }

}, 500);

}).listen(80);

http.createServer(function (req, res) {

 res.writeHead(200, { 'Content-Type': 'text/plain' });

 res.write('8080 request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));

 res.end();

}).listen(8080);

http.createServer(function (req, res) {

 res.writeHead(200, { 'Content-Type': 'text/plain' });

 res.write('8081 request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));

 res.end();

}).listen(8081);

0コメント

  • 1000 / 1000