diff --git a/lib/request.js b/lib/request.js index 79273448c..0b0b2625a 100644 --- a/lib/request.js +++ b/lib/request.js @@ -252,8 +252,10 @@ module.exports = { get host() { const proxy = this.app.proxy; let host = proxy && this.get('X-Forwarded-Host'); - if (this.req.httpVersionMajor >= 2) host = this.get(':authority'); - host = host || this.get('Host'); + if (!host) { + if (this.req.httpVersionMajor >= 2) host = this.get(':authority'); + if (!host) host = this.get('Host'); + } if (!host) return ''; return host.split(/\s*,\s*/)[0]; }, diff --git a/test/request/host.js b/test/request/host.js index f3934e647..0ad94868e 100644 --- a/test/request/host.js +++ b/test/request/host.js @@ -53,22 +53,45 @@ describe('req.host', () => { describe('when X-Forwarded-Host is present', () => { describe('and proxy is not trusted', () => { - it('should be ignored', () => { + it('should be ignored on HTTP/1', () => { const req = request(); req.header['x-forwarded-host'] = 'bar.com'; req.header.host = 'foo.com'; assert.equal(req.host, 'foo.com'); }); + + it('should be ignored on HTTP/2', () => { + const req = request({ + 'httpVersionMajor': 2, + 'httpVersion': '2.0' + }); + req.header['x-forwarded-host'] = 'proxy.com:8080'; + req.header[':authority'] = 'foo.com:3000'; + req.header.host = 'bar.com:8000'; + assert.equal(req.host, 'foo.com:3000'); + }); }); describe('and proxy is trusted', () => { - it('should be used', () => { + it('should be used on HTTP/1', () => { const req = request(); req.app.proxy = true; req.header['x-forwarded-host'] = 'bar.com, baz.com'; req.header.host = 'foo.com'; assert.equal(req.host, 'bar.com'); }); + + it('should be used on HTTP/2', () => { + const req = request({ + 'httpVersionMajor': 2, + 'httpVersion': '2.0' + }); + req.app.proxy = true; + req.header['x-forwarded-host'] = 'proxy.com:8080'; + req.header[':authority'] = 'foo.com:3000'; + req.header.host = 'bar.com:8000'; + assert.equal(req.host, 'proxy.com:8080'); + }); }); }); });