diff --git a/mkdocs/livereload/__init__.py b/mkdocs/livereload/__init__.py index 83803e0a96..c9f7afa8e7 100644 --- a/mkdocs/livereload/__init__.py +++ b/mkdocs/livereload/__init__.py @@ -183,10 +183,10 @@ def condition(): if path == "/js/livereload.js": file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "livereload.js") elif path.startswith(self.mount_path): + rel_file_path = path[len(self.mount_path):].lstrip("/") if path.endswith("/"): - path += "index.html" - path = path[len(self.mount_path):] - file_path = os.path.join(self.root, path.lstrip("/")) + rel_file_path += "index.html" + file_path = os.path.join(self.root, rel_file_path) elif path == "/": start_response("302 Found", [("Location", self.mount_path)]) return [] @@ -201,9 +201,12 @@ def condition(): try: file = open(file_path, "rb") except OSError: + if not path.endswith("/") and os.path.isfile(os.path.join(file_path, "index.html")): + start_response("302 Found", [("Location", path + "/")]) + return [] return None # Not found - if path.endswith(".html"): + if file_path.endswith(".html"): with file: content = file.read() content = self._inject_js_into_html(content, epoch) diff --git a/mkdocs/tests/livereload_tests.py b/mkdocs/tests/livereload_tests.py index cafa21dc86..6ec81fda85 100644 --- a/mkdocs/tests/livereload_tests.py +++ b/mkdocs/tests/livereload_tests.py @@ -293,7 +293,7 @@ def test_serves_modified_html(self, site_dir): self.assertRegex(output, fr"^foobar{SCRIPT_REGEX}$") @tempdir({"index.html": "aaa", "foo/index.html": "bbb"}) - def test_serves_modified_index(self, site_dir): + def test_serves_directory_index(self, site_dir): with testing_server(site_dir) as server: headers, output = do_request(server, "GET /") self.assertRegex(output, fr"^aaa{SCRIPT_REGEX}$") @@ -301,8 +301,21 @@ def test_serves_modified_index(self, site_dir): self.assertEqual(headers.get("content-type"), "text/html") self.assertEqual(headers.get("content-length"), str(len(output))) - _, output = do_request(server, "GET /foo/") - self.assertRegex(output, fr"^bbb{SCRIPT_REGEX}$") + for path in "/foo/", "/foo/index.html": + _, output = do_request(server, "GET /foo/") + self.assertRegex(output, fr"^bbb{SCRIPT_REGEX}$") + + with self.assertLogs("mkdocs.livereload"): + headers, _ = do_request(server, "GET /foo/index.html/") + self.assertEqual(headers["_status"], "404 Not Found") + + @tempdir({"foo/bar/index.html": "aaa"}) + def test_redirects_to_directory(self, site_dir): + with testing_server(site_dir, mount_path="/sub") as server: + with self.assertLogs("mkdocs.livereload"): + headers, _ = do_request(server, "GET /sub/foo/bar") + self.assertEqual(headers["_status"], "302 Found") + self.assertEqual(headers.get("location"), "/sub/foo/bar/") @tempdir({"я.html": "aaa", "测试2/index.html": "bbb"}) def test_serves_with_unicode_characters(self, site_dir):