Skip to content

Commit 3bbb2c8

Browse files
author
blahed
committed
determine x-forwarded-port from host header
`req.remotePort' returns the ephemeral port, which is not useful. node v0.10.0 added `req.localPort' which returns what we want, but we want to maintain backwards compatibility. Fixes http-party#341 & http-party#227
1 parent de0928f commit 3bbb2c8

File tree

1 file changed

+15
-4
lines changed

1 file changed

+15
-4
lines changed

lib/node-http-proxy/http-proxy.js

+15-4
Original file line numberDiff line numberDiff line change
@@ -149,11 +149,11 @@ HttpProxy.prototype.proxyRequest = function (req, res, buffer) {
149149
}
150150

151151
if (req.headers['x-forwarded-port']) {
152-
var portToAppend = "," + req.connection.remotePort || req.socket.remotePort;
152+
var portToAppend = "," + getPortFromHostHeader(req);
153153
req.headers['x-forwarded-port'] += portToAppend;
154154
}
155155
else {
156-
req.headers['x-forwarded-port'] = req.connection.remotePort || req.socket.remotePort;
156+
req.headers['x-forwarded-port'] = getPortFromHostHeader(req);
157157
}
158158

159159
if (req.headers['x-forwarded-proto']) {
@@ -480,11 +480,11 @@ HttpProxy.prototype.proxyWebSocketRequest = function (req, socket, upgradeHead,
480480
}
481481

482482
if (req.headers['x-forwarded-port']) {
483-
var portToAppend = "," + req.connection.remotePort || socket.remotePort;
483+
var portToAppend = "," + getPortFromHostHeader(req);
484484
req.headers['x-forwarded-port'] += portToAppend;
485485
}
486486
else {
487-
req.headers['x-forwarded-port'] = req.connection.remotePort || socket.remotePort;
487+
req.headers['x-forwarded-port'] = getPortFromHostHeader(req);
488488
}
489489

490490
if (req.headers['x-forwarded-proto']) {
@@ -947,6 +947,17 @@ HttpProxy.prototype._forwardRequest = function (req) {
947947
});
948948
};
949949

950+
function getPortFromHostHeader(req) {
951+
var portMatch = req.headers.host.match(/:(\d+)$/);
952+
953+
if(portMatch) {
954+
return parseInt(portMatch[1]);
955+
}
956+
else {
957+
return getProto(req) === 'https' ? 443 : 80;
958+
}
959+
}
960+
950961
function getProto(req) {
951962
return req.isSpdy ? 'https' : (req.connection.pair ? 'https' : 'http');
952963
}

0 commit comments

Comments
 (0)