http-proxyでプロキシ

以前、connectとhttp-proxyでバーチャルホスト - 四角革命前夜でhttp-proxyは試したのだけど、サブドメインで試しただけでディレクトリでは試してなかったのでやってみた。

#!/usr/bin/env node

var http = require('http'),
    httpProxy = require('http-proxy'),
    proxyServer, server1, server2;

proxyServer = httpProxy.createServer({
  hostnameOnly: false,
  router: {
   'localhost/aaaa': '127.0.0.1:4000',
   'localhost/bbbb': '127.0.0.1:5000'
  }
});
proxyServer.listen(3000);

server1 = http.createServer(function (req, res) {
  res.end('!!! this is server 1 !!!\n');
});
server2 = http.createServer(function (req, res) {
  res.end('??? this is server 2 ???\n');
});

server1.listen(4000);
server2.listen(5000);

変わったところはhostnameOnlyがfalseに、あとrouterの値をちょっと変えただけかな。ラクチンだなあ。

$ curl http://localhost:3000/aaaa
!!! this is server 1 !!!
$ curl http://localhost:3000/bbbb
??? this is server 2 ???
$ curl http://localhost:3000/

思った通りに動作してくれました。