-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.js
More file actions
59 lines (47 loc) · 1.64 KB
/
server.js
File metadata and controls
59 lines (47 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
var httpProxy = require('http-proxy')
, url = require('url')
, http = require('http')
exports.handleRequest = function(
subProxyHost, // e.g., localhost
port, // port to host on
req,
res,
proxy) { // http-proxy's proxy argument
if(port != 80)
subProxyHost += ':' + port
if(req.headers.host.indexOf(subProxyHost) ===
req.headers.host.length - subProxyHost.length) {
// infer the proxy domain
var proxyDomain = req.headers.host.
slice(0, req.headers.host.length - subProxyHost.length -1)
var originalHost = req.headers.host
// replace the host in the request
req.headers.host = proxyDomain
// intercept calls to writeHead, so that we write the new location there
var oldWriteHead = res.writeHead
res.writeHead = function(statusCode, headers) {
if(headers.location) {
// replace the host in the response
var parsedUrl = url.parse(headers.location)
if(parsedUrl.host === req.headers.host) {
parsedUrl.host = originalHost + (port === 80 ? '' : ':' + port)
headers.location = url.format(parsedUrl)
}
}
// now that we've overwritten the header the node-http-proxy passes,
// we pass it along
oldWriteHead.apply(res, arguments)
}
proxy.proxyRequest(req, res, {
host: proxyDomain,
port: 80
})
}
else {
res.statusCode = 500
res.setHeader('Content-Type', 'text/plain')
res.end('Internal Server Error: failed to identify host "' +
req.headers.host + '"; expecting something ending with "' +
subProxyHost +'"')
}
}