Skip to content
This repository was archived by the owner on Jan 31, 2020. It is now read-only.

Commit 43f4bce

Browse files
committed
Use the Host port when port forwarding is detected
In vagrant and other systems, you often have a port on the host forwarding to a port on the client box. In terms of ServerUrl, the port on the host server is the public one that should be used. Prior to this patch ServerUrl was detecting both the port from the Host header, as well as SERVER_PORT, and using *both* in generated URLs. As an example, given: HTTP_HOST: localhost:10088 SERVER_PORT: 10081 ServerUrl would generate the host "localhost:10088:10081", when it should be generating "localhost:10088". This patch corrects the situation.
1 parent d74c7c9 commit 43f4bce

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

src/Helper/ServerUrl.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,16 @@ protected function detectHost()
8585
$this->setHost(substr($_SERVER['HTTP_HOST'], 0, 0-strlen($portStr)));
8686
return;
8787
}
88+
89+
// If the Host header contains a port, and it differs from the
90+
// SERVER_PORT, use the port from the Host header. Typically
91+
// this is a situation where port-forwarding is in use, and you
92+
// want to present a URI using the public port.
93+
if (preg_match('/^(?P<host>.*?):(?P<port>\d+)$/', $_SERVER['HTTP_HOST'], $matches)) {
94+
$this->setPort((int) $matches['port']);
95+
$this->setHost(rtrim($matches['host']));
96+
return;
97+
}
8898
}
8999

90100
$this->setHost($_SERVER['HTTP_HOST']);

test/Helper/ServerUrlTest.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,4 +219,12 @@ public function testCanUseXForwardedPortIfProvided()
219219
$url->setUseProxy(true);
220220
$this->assertEquals('http://www.secondhost.org:8888', $url->__invoke());
221221
}
222+
223+
public function testUsesHostHeaderWhenPortForwardingDetected()
224+
{
225+
$_SERVER['HTTP_HOST'] = 'localhost:10088';
226+
$_SERVER['SERVER_PORT'] = 10081;
227+
$url = new Helper\ServerUrl();
228+
$this->assertEquals('http://localhost:10088', $url->__invoke());
229+
}
222230
}

0 commit comments

Comments
 (0)