Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow X-Forwarded-Port header to override the default SERVER_PORT when reversing URLs #619

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion django/http/request.py
Expand Up @@ -60,7 +60,7 @@ def get_host(self):
else: else:
# Reconstruct the host using the algorithm from PEP 333. # Reconstruct the host using the algorithm from PEP 333.
host = self.META['SERVER_NAME'] host = self.META['SERVER_NAME']
server_port = str(self.META['SERVER_PORT']) server_port = str(self.META.get('HTTP_X_FORWARDED_PORT', self.META['SERVER_PORT']))
if server_port != ('443' if self.is_secure() else '80'): if server_port != ('443' if self.is_secure() else '80'):
host = '%s:%s' % (host, server_port) host = '%s:%s' % (host, server_port)


Expand Down
18 changes: 18 additions & 0 deletions tests/regressiontests/requests/tests.py
Expand Up @@ -119,6 +119,24 @@ def test_http_get_host(self):
} }
self.assertEqual(request.get_host(), 'internal.com:8042') self.assertEqual(request.get_host(), 'internal.com:8042')


# Check if HTTP_HOST isn't provided, and X-FORWARDED-PORT is set
request = HttpRequest()
request.META = {
'SERVER_NAME': 'internal.com',
'SERVER_PORT': 8080,
'HTTP_X_FORWARDED_PORT': 80,
}
self.assertEqual(request.get_host(), 'internal.com')

# Check if HTTP_HOST isn't provided, and X-FORWARDED-PORT is set to non-standard port
request = HttpRequest()
request.META = {
'SERVER_NAME': 'internal.com',
'SERVER_PORT': 8080,
'HTTP_X_FORWARDED_PORT': 8042,
}
self.assertEqual(request.get_host(), 'internal.com:8042')

# Poisoned host headers are rejected as suspicious # Poisoned host headers are rejected as suspicious
legit_hosts = [ legit_hosts = [
'example.com', 'example.com',
Expand Down