nginx + node.js + socket.io を同じサーバーかつ同じポートで動かす
node.jsのsocket.ioのポートと、nginxのポートを同じポートで運用したい場合は
nginxのリバースプロキシの機能を利用すると良い。
前提
- httpポートは80
- ドメインは「hogehoge.com」
- node.jsのsocket.ioサーバーはポート12345でListen
- socket.io用のサブドメインを「socket.hogehoge.com」とする
サーバー側の設定
nginxの設定ファイルにて、以下の様にリバースプロキシの設定をする。
#リバースプロキシの設定 server { listen 80; server_name socket.hogehoge.com; location / { proxy_pass http://localhost:12345; } location /socket.io/ { proxy_pass http://localhost:12345; #proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } } # 通常のhttpサーバーの設定ですので割愛 server { listen 80; server_name hogehoge.com; ....色々.... }
クライアント側のサンプルコード
クライアント側では以下の様にしてsocket.ioのスクリプトをロード
<script src="http://socket.hogehoge.com/socket.io/socket.io.js"></script>
socket.ioのconnect時は以下の様にする。
var socket = io.connect('http://socket.hogehoge.com');