connectとhttp-proxyでバーチャルホスト
バーチャルホスト関連のことを試さないといけなかったので、いろいろ調べつつ早速試してみたのでした。
環境:OS X 10.7.5 / node.js 0.8.14
モジュール
とりあえず調べて出てきたのが以下の2つ。
- Connect
- http-proxy
まあ、両方とも有名なモジュールですね。
(後者はこれを調べるまで知らなかったけど……)
下準備
hostsをちょっとだけ書き換えます。まずはバックアップを。
$ sudo cp /etc/hosts{,.bak} $ sudo vim /etc/hosts
で、以下のように書き換えます。
-127.0.0.1 localhost +127.0.0.1 localhost server1.localhost server2.localhost
サブドメインでアクセスできるように追加しています。
Connect
Conenctでのバーチャルホストはvhostミドルウェアを使って実現します。
まずはモジュールのインストールを。
$ npm i connect
続いてソースコードを書きます。具体的には以下のようなコードです。
index.js
#!/usr/bin/env node var http = require('http'), connect = require('connect'), server1, server2, mainServer; server1 = http.createServer(function (req, res) { res.end('### this is server1 ###'); }); server2 = http.createServer(function (req, res) { res.end('*** this is server2 ***'); }); mainServer = http.createServer(function (req, res) { res.end('%%% this is main server %%%'); }); connect() .use(connect.vhost('server1.*', server1)) .use(connect.vhost('server2.*', server2)) .use(connect.vhost('*', mainServer)) .listen(3000);
connect.vhostの第2引数にhttp.Serverのインスタンスを渡します。
listenはしていなくても良いみたいです。
確認してみると……
$ node index.js & $ curl http://localhost:3000 %%% this is main server %%% $ curl http://server1.localhost:3000 ### this is server1 ### $ curl http://server2.localhost:3000 *** this is server2 ***
ちゃんと振り分けられているようです。
http-proxy
続いてhttp-proxyモジュールを使ってのバーチャルホストを試します。
モジュールのインストールから。
$ npm i http-proxy
続いてソースコードを。
index.js
#!/usr/bin/env node var http = require('http'), httpProxy = require('http-proxy'), proxyServer, server1, server2; proxyServer = httpProxy.createServer({ hostnameOnly: true, router: { 'server1.localhost': '127.0.0.1:4000', 'server2.localhost': '127.0.0.1:5000' } }); proxyServer.listen(3000); server1 = http.createServer(function (req, res) { res.end('!!! this is server 1 !!!'); }); server2 = http.createServer(function (req, res) { res.end('??? this is server 2 ???'); }); server1.listen(4000); server2.listen(5000);
httpProxyを生成して、ポートを設定してあげるだけです。
これもまた確認してみると……
$ node index.js & $ curl http://server1.localhost:3000 !!! this is server 1 !!! $ curl http://server2.localhost:3000 ??? this is server 2 ???
これもちゃんと振り分けられているみたいです。
というわけで、node.jsで簡単なバーチャルホスト環境の作成でした。
nginxとか使ったりとか、いろいろ方法はあるのでしょうけど、手っ取り早くできるのは良いかもしれません。