Don't drop explict port on HTTPS redirects (#382)

This commit is contained in:
Tom Christie 2019-02-11 10:26:18 +00:00 committed by GitHub
parent 208b4aa207
commit 204d1b596f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 13 additions and 2 deletions

View File

@ -9,9 +9,10 @@ class HTTPSRedirectMiddleware:
def __call__(self, scope: Scope) -> ASGIInstance: def __call__(self, scope: Scope) -> ASGIInstance:
if scope["type"] in ("http", "websocket") and scope["scheme"] in ("http", "ws"): if scope["type"] in ("http", "websocket") and scope["scheme"] in ("http", "ws"):
redirect_scheme = {"http": "https", "ws": "wss"}[scope["scheme"]]
url = URL(scope=scope) url = URL(scope=scope)
url = url.replace(scheme=redirect_scheme, netloc=url.hostname) redirect_scheme = {"http": "https", "ws": "wss"}[url.scheme]
netloc = url.hostname if url.port in (80, 443) else url.netloc
url = url.replace(scheme=redirect_scheme, netloc=netloc)
return RedirectResponse(url, status_code=301) return RedirectResponse(url, status_code=301)
return self.app(scope) return self.app(scope)

View File

@ -21,3 +21,13 @@ def test_https_redirect_middleware():
response = client.get("/", allow_redirects=False) response = client.get("/", allow_redirects=False)
assert response.status_code == 301 assert response.status_code == 301
assert response.headers["location"] == "https://testserver/" assert response.headers["location"] == "https://testserver/"
client = TestClient(app, base_url="http://testserver:80")
response = client.get("/", allow_redirects=False)
assert response.status_code == 301
assert response.headers["location"] == "https://testserver/"
client = TestClient(app, base_url="http://testserver:123")
response = client.get("/", allow_redirects=False)
assert response.status_code == 301
assert response.headers["location"] == "https://testserver:123/"