Node.js VirtualHost
-
개요
Apache/Nginx를 설치하지 않고 Node.js로 VirtualHost를 구현하는 방법으로
node-http-proxy
를 사용합니다.node-http-proxy is an HTTP programmable proxying library that supports websockets. It is suitable for implementing components such as reverse proxies and load balancers.
80 포트를 접근하므로 root 권한이 필요할 수 있습니다.
설치
npm install http-proxy lodash node httpd.js
httpd.js
const http = require('http'); const httpProxy = require('http-proxy'); const _ = require('lodash'); const virtualHost = { // Proxy Web 'tested.co.kr': { target: { host: 'localhost', port: 8000 } }, // Proxy WebSocket 'ws.tested.co.kr': { target: { host: 'localhost', port: 8010 }, ws: true }, // Proxy Path 'temp.tested.co.kr': { target: { host: 'localhost', port: 8100, path: '/temp' } }, // Redirect main: 'http://tested.co.kr', }; // https://github.com/nodejitsu/node-http-proxy#options const proxy = httpProxy.createProxyServer({ xfwd: true }); proxy.on('error', (err, req) => { console.error('Error', err); }); // Web const proxyServer = http.createServer((req, res) => { // 설정된 호스트가 아니라면 메인으로 const target = virtualHost[req.headers.host] || virtualHost.main; // 프록시 설정이 아니면 해당 주소로 리다이렉트 if (!_.isObject(target)) { res.writeHead(308, { Location: target }); res.end(); } else { proxy.web(req, res, target); } }); // WebSocket proxyServer.on('upgrade', (req, socket, head) => { const target = virtualHost[req.headers.host]; proxy.ws(req, socket, head, target); }); console.log('Listening on Port 80'); proxyServer.listen(80);
링크
https://github.com/nodejitsu/node-http-proxy
https://github.com/lodash/lodash2017-03-10