diff --git a/Lib/http/server.py b/Lib/http/server.py
index 64f766f9bc2c1b..c152d9a833b7da 100644
--- a/Lib/http/server.py
+++ b/Lib/http/server.py
@@ -846,12 +846,11 @@ def list_directory(self, path):
except UnicodeDecodeError:
displaypath = urllib.parse.unquote(self.path)
displaypath = html.escape(displaypath, quote=False)
- enc = sys.getfilesystemencoding()
title = f'Directory listing for {displaypath}'
r.append('')
r.append('')
r.append('
')
- r.append(f'')
+ r.append('')
r.append('')
r.append(f'{title}\n')
r.append(f'\n{title}
')
@@ -871,12 +870,12 @@ def list_directory(self, path):
errors='surrogatepass'),
html.escape(displayname, quote=False)))
r.append('\n
\n\n\n')
- encoded = '\n'.join(r).encode(enc, 'surrogateescape')
+ encoded = '\n'.join(r).encode('utf-8', 'surrogateescape')
f = io.BytesIO()
f.write(encoded)
f.seek(0)
self.send_response(HTTPStatus.OK)
- self.send_header("Content-type", "text/html; charset=%s" % enc)
+ self.send_header("Content-type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(encoded)))
self.end_headers()
return f
diff --git a/Misc/NEWS.d/next/Library/2025-05-13-16-51-00.gh-issue-133889.ashdsf.rst b/Misc/NEWS.d/next/Library/2025-05-13-16-51-00.gh-issue-133889.ashdsf.rst
new file mode 100644
index 00000000000000..5ba0d921414e2b
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2025-05-13-16-51-00.gh-issue-133889.ashdsf.rst
@@ -0,0 +1 @@
+Encode file paths with utf-8 in :meth:`http.SimpleHTTPRequestHandler.list_directory`.