diff --git a/lib/http-proxy/passes/web-outgoing.js b/lib/http-proxy/passes/web-outgoing.js index 99f886477..977f1f747 100644 --- a/lib/http-proxy/passes/web-outgoing.js +++ b/lib/http-proxy/passes/web-outgoing.js @@ -50,7 +50,14 @@ var redirectRegex = /^30(1|2|7|8)$/; if ((options.hostRewrite || options.autoRewrite || options.protocolRewrite) && proxyRes.headers['location'] && redirectRegex.test(proxyRes.statusCode)) { + var target = url.parse(options.target); var u = url.parse(proxyRes.headers['location']); + + // make sure the redirected host matches the target host before rewriting + if (target.host != u.host) { + return; + } + if (options.hostRewrite) { u.host = options.hostRewrite; } else if (options.autoRewrite) { diff --git a/test/lib-http-proxy-passes-web-outgoing-test.js b/test/lib-http-proxy-passes-web-outgoing-test.js index 7aef725cc..5b91c0bb2 100644 --- a/test/lib-http-proxy-passes-web-outgoing-test.js +++ b/test/lib-http-proxy-passes-web-outgoing-test.js @@ -49,6 +49,20 @@ describe('lib/http-proxy/passes/web-outgoing.js', function () { httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options); expect(this.proxyRes.headers.location).to.eql('http://ext-manual.com/'); }); + + it('not when the redirected location does not match target host', function() { + this.proxyRes.statusCode = 302; + this.proxyRes.headers.location = "http://some-other/"; + httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options); + expect(this.proxyRes.headers.location).to.eql('http://some-other/'); + }); + + it('not when the redirected location does not match target port', function() { + this.proxyRes.statusCode = 302; + this.proxyRes.headers.location = "http://backend.com:8080/"; + httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options); + expect(this.proxyRes.headers.location).to.eql('http://backend.com:8080/'); + }); }); context('rewrites location host with autoRewrite', function() { @@ -74,6 +88,20 @@ describe('lib/http-proxy/passes/web-outgoing.js', function () { httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options); expect(this.proxyRes.headers.location).to.eql('http://backend.com/'); }); + + it('not when the redirected location does not match target host', function() { + this.proxyRes.statusCode = 302; + this.proxyRes.headers.location = "http://some-other/"; + httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options); + expect(this.proxyRes.headers.location).to.eql('http://some-other/'); + }); + + it('not when the redirected location does not match target port', function() { + this.proxyRes.statusCode = 302; + this.proxyRes.headers.location = "http://backend.com:8080/"; + httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options); + expect(this.proxyRes.headers.location).to.eql('http://backend.com:8080/'); + }); }); context('rewrites location protocol with protocolRewrite', function() {