Created
March 14, 2017 01:26
-
-
Save CatsMiaow/9a67a3c7a733d8ee7b1ffab52fba2f36 to your computer and use it in GitHub Desktop.
Node.js VirtualHost
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment