Skip to content

Commit 4964242

Browse files
fengmk2dead-horse
authored andcommitted
fix: use X-Forwarded-Host first on app.proxy present (#1263)
1 parent e01cc5a commit 4964242

File tree

2 files changed

+29
-4
lines changed

2 files changed

+29
-4
lines changed

lib/request.js

+4-2
Original file line numberDiff line numberDiff line change
@@ -252,8 +252,10 @@ module.exports = {
252252
get host() {
253253
const proxy = this.app.proxy;
254254
let host = proxy && this.get('X-Forwarded-Host');
255-
if (this.req.httpVersionMajor >= 2) host = this.get(':authority');
256-
host = host || this.get('Host');
255+
if (!host) {
256+
if (this.req.httpVersionMajor >= 2) host = this.get(':authority');
257+
if (!host) host = this.get('Host');
258+
}
257259
if (!host) return '';
258260
return host.split(/\s*,\s*/)[0];
259261
},

test/request/host.js

+25-2
Original file line numberDiff line numberDiff line change
@@ -53,22 +53,45 @@ describe('req.host', () => {
5353

5454
describe('when X-Forwarded-Host is present', () => {
5555
describe('and proxy is not trusted', () => {
56-
it('should be ignored', () => {
56+
it('should be ignored on HTTP/1', () => {
5757
const req = request();
5858
req.header['x-forwarded-host'] = 'bar.com';
5959
req.header.host = 'foo.com';
6060
assert.equal(req.host, 'foo.com');
6161
});
62+
63+
it('should be ignored on HTTP/2', () => {
64+
const req = request({
65+
'httpVersionMajor': 2,
66+
'httpVersion': '2.0'
67+
});
68+
req.header['x-forwarded-host'] = 'proxy.com:8080';
69+
req.header[':authority'] = 'foo.com:3000';
70+
req.header.host = 'bar.com:8000';
71+
assert.equal(req.host, 'foo.com:3000');
72+
});
6273
});
6374

6475
describe('and proxy is trusted', () => {
65-
it('should be used', () => {
76+
it('should be used on HTTP/1', () => {
6677
const req = request();
6778
req.app.proxy = true;
6879
req.header['x-forwarded-host'] = 'bar.com, baz.com';
6980
req.header.host = 'foo.com';
7081
assert.equal(req.host, 'bar.com');
7182
});
83+
84+
it('should be used on HTTP/2', () => {
85+
const req = request({
86+
'httpVersionMajor': 2,
87+
'httpVersion': '2.0'
88+
});
89+
req.app.proxy = true;
90+
req.header['x-forwarded-host'] = 'proxy.com:8080';
91+
req.header[':authority'] = 'foo.com:3000';
92+
req.header.host = 'bar.com:8000';
93+
assert.equal(req.host, 'proxy.com:8080');
94+
});
7295
});
7396
});
7497
});

0 commit comments

Comments
 (0)