diff --git a/Lib/http/server.py b/Lib/http/server.py index 02e9cc2af83..ac53550a972 100644 --- a/Lib/http/server.py +++ b/Lib/http/server.py @@ -648,10 +648,14 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): path = self.translate_path(self.path) f = None if os.path.isdir(path): - if not self.path.endswith('/'): + parts = urllib.parse.urlsplit(self.path) + if not parts.path.endswith('/'): # redirect browser - doing basically what apache does self.send_response(HTTPStatus.MOVED_PERMANENTLY) - self.send_header("Location", self.path + "/") + new_parts = (parts[0], parts[1], parts[2] + '/', + parts[3], parts[4]) + new_url = urllib.parse.urlunsplit(new_parts) + self.send_header("Location", new_url) self.end_headers() return None for index in "index.html", "index.htm": diff --git a/Lib/test/test_httpservers.py b/Lib/test/test_httpservers.py index 97713cd0431..a31db5b57b8 100644 --- a/Lib/test/test_httpservers.py +++ b/Lib/test/test_httpservers.py @@ -305,6 +305,12 @@ class SimpleHTTPServerTestCase(BaseTestCase): self.check_status_and_reason(response, 200) response = self.request(self.tempdir_name) self.check_status_and_reason(response, 301) + response = self.request(self.tempdir_name + '/?hi=2') + self.check_status_and_reason(response, 200) + response = self.request(self.tempdir_name + '?hi=1') + self.check_status_and_reason(response, 301) + self.assertEqual(response.getheader("Location"), + self.tempdir_name + "/?hi=1") response = self.request('/ThisDoesNotExist') self.check_status_and_reason(response, 404) response = self.request('/' + 'ThisDoesNotExist' + '/') diff --git a/Misc/NEWS b/Misc/NEWS index 97b329aa491..45dd5b4307f 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -196,6 +196,9 @@ Core and Builtins Library ------- +- Issue #23112: Fix SimpleHTTPServer to correctly carry the query string and + fragment when it redirects to add a trailing slash. + - Issue #21793: Added http.HTTPStatus enums (i.e. HTTPStatus.OK, HTTPStatus.NOT_FOUND). Patch by Demian Brecht.