Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
node-http-proxyを使ったいわゆるバーチャルホスト対応Webサーバー(WebSocket対応版)
var http = require('http'),
httpProxy = require('http-proxy'),
logger = require('./logger');
// localhost:8001 に普通のExpressアプリ -> http://test.nov1.jp/
// localhost:8002 にWebSocketを使ったExpressアプリ -> http://😄.nov1.jp/, http://chat.nov1.jp/
// Proxy for Chat app
var proxy = new httpProxy.HttpProxy({
target: {
host: 'localhost',
port: 8002
}});
// Proxy for Test app
var testProxy = new httpProxy.HttpProxy({
target: {
host: 'localhost',
port: 8001
}});
var webSocketProxy = new httpProxy.HttpProxy({
target: {
host: 'localhost',
port: 8002
}});
var server = http.createServer(logger(true, function ( req, res ) {
//console.log(req.headers.host);
//console.log(req.headers);
if (req.headers.host == 'test.nov1.jp' || req.headers.host == 'xn--tu8h.nov1.jp') {
testProxy.proxyRequest( req, res );
} else if (req.headers.host == 'chat.nov1.jp' || req.headers.host == 'xn--i28h.nov1.jp') {
proxy.proxyRequest( req, res );
} else {
res.writeHead(404);
res.end();
}
}));
server.on( 'upgrade', function( req, socket, head ) {
req.headers['x-forwarded-for'] = req.connection.remoteAddress || req.connection.socket.remoteAddress;
//console.log(req.headers);
webSocketProxy.proxyWebSocketRequest( req, socket, head );
});
server.listen(80);
// c.f. http://blog.nodejitsu.com/http-proxy-middlewares
var fs = require('fs'),
http = require('http');
var logFile = fs.createWriteStream('/root/requests.log', {flags: 'a', encoding: 'utf8'});
module.exports = function (logging, next) {
return function (request, response) {
if (logging) {
logFile.write(JSON.stringify(request.headers, true, 2));
}
next(request, response);
}
}
@novi

This comment has been minimized.

Copy link
Owner Author

commented Feb 14, 2012

  • test._でもchat._でも無い時は404を返す
  • WebSocketでオリジナルIPが抜けてしまうのでヘッダのx-forwarded-forに入れる
@novi

This comment has been minimized.

Copy link
Owner Author

commented Feb 15, 2012

  • Loggerを追加。飛んできたリクエストヘッダをすべてJSONでファイルに書き出す。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.