mirror of https://github.com/encode/starlette.git
Don't drop explict port on HTTPS redirects (#382)
This commit is contained in:
parent
208b4aa207
commit
204d1b596f
|
@ -9,9 +9,10 @@ class HTTPSRedirectMiddleware:
|
|||
|
||||
def __call__(self, scope: Scope) -> ASGIInstance:
|
||||
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.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 self.app(scope)
|
||||
|
|
|
@ -21,3 +21,13 @@ def test_https_redirect_middleware():
|
|||
response = client.get("/", allow_redirects=False)
|
||||
assert response.status_code == 301
|
||||
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/"
|
||||
|
|
Loading…
Reference in New Issue