Nginxでサブディレクリへのアクセスをsocket.ioに転送する方法を調査しました。
サブディレクトリで転送する場合は、socket.ioのアプリ側で対応が必要になります。
以下はsocket.ioはNginxと同一サーバー、ポート3000番で動作させる例です。
Nginxはバージョン1.3.13以上です。このバージョンから単体でwebsocketに対応するようになりました。
socket.ioに転送するURLは下記の通りです。
http://example.com/node/
Nginxの設定ファイル
/node/へのアクセスをバックエンドsocket.ioのURLに転送します。
upstream backend {
server 127.0.0.1:3000;
}
server {
# 省略
location /node/ {
proxy_pass http://backend/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_redirect off;
}
}
socket.ioのサンプルコード
app.js
ルートで動作させる場合と違いはありません。
var http = require('http'),
fs = require('fs'),
// NEVER use a Sync function except at start-up!
index = fs.readFileSync(__dirname + '/index.html');
// Send index.html to all requests
var app = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(index);
});
// Socket.io server listens to our app
var io = require('socket.io').listen(app);
// Send current time to all connected clients
function sendTime() {
io.sockets.emit('time', { time: new Date().toJSON() });
}
// Send current time every 10 secs
setInterval(sendTime, 10000);
// Emit welcome message on connection
io.sockets.on('connection', function(socket) {
socket.emit('welcome', { message: 'Welcome!' });
socket.on('i am client', console.log);
});
app.listen(3000);
