Skip to content

gh-100463: Add handling for extensionless URLs in http.server #100464

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 13 additions & 7 deletions Doc/library/http.server.rst
Original file line number Diff line number Diff line change
Expand Up @@ -376,13 +376,16 @@ provides three different variants:
:func:`os.listdir` to scan the directory, and returns a ``404`` error
response if the :func:`~os.listdir` fails.

If the request was mapped to a file, it is opened. Any :exc:`OSError`
exception in opening the requested file is mapped to a ``404``,
``'File not found'`` error. If there was a ``'If-Modified-Since'``
header in the request, and the file was not modified after this time,
a ``304``, ``'Not Modified'`` response is sent. Otherwise, the content
type is guessed by calling the :meth:`guess_type` method, which in turn
uses the *extensions_map* variable, and the file contents are returned.
If the request was mapped to a file, it is opened. If the file does not
exist, and the URL does not contain an extension, the path is instead
checked for the file with the additional extension ``.html`` or ``.htm``
(in that order) and that is opened. Any :exc:`OSError` exception in
opening the requested file is mapped to a ``404``, ``'File not found'``
error. If there was a ``'If-Modified-Since'`` header in the request, and
the file was not modified after this time, a ``304``, ``'Not Modified'``
response is sent. Otherwise, the content type is guessed by calling the
:meth:`guess_type` method, which in turn uses the *extensions_map*
variable, and the file contents are returned.

A ``'Content-type:'`` header with the guessed content type is output,
followed by a ``'Content-Length:'`` header with the file's size and a
Expand All @@ -398,6 +401,9 @@ provides three different variants:
.. versionchanged:: 3.7
Support of the ``'If-Modified-Since'`` header.

.. versionchanged:: 3.12
Checks for presence of HTML file in absence of an extension.

The :class:`SimpleHTTPRequestHandler` class can be used in the following
manner in order to create a very basic webserver serving files relative to
the current directory::
Expand Down
13 changes: 12 additions & 1 deletion Lib/http/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -653,6 +653,7 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
"""

index_pages = ["index.html", "index.htm"]
default_extensions = [".html", ".htm"]
server_version = "SimpleHTTP/" + __version__
extensions_map = _encodings_map_default = {
'.gz': 'application/gzip',
Expand All @@ -661,11 +662,14 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
'.xz': 'application/x-xz',
}

def __init__(self, *args, directory=None, index_pages=None, **kwargs):
def __init__(self, *args, directory=None, index_pages=None,
default_extensions=None, **kwargs):
if directory is None:
directory = os.getcwd()
if index_pages is not None:
self.index_pages = index_pages
if default_extensions is not None:
self.default_extensions = default_extensions
self.directory = os.fspath(directory)
super().__init__(*args, **kwargs)

Expand Down Expand Up @@ -725,6 +729,13 @@ def send_head(self):
if path.endswith("/"):
self.send_error(HTTPStatus.NOT_FOUND, "File not found")
return None
# Special case for URLs with default extension.
if os.path.splitext(path)[1] == "":
if not os.path.exists(path):
for extension in self.default_extensions:
if os.path.exists(path + extension):
path += extension
break
try:
f = open(path, 'rb')
except OSError:
Expand Down
15 changes: 15 additions & 0 deletions Lib/test/test_httpservers.py
Original file line number Diff line number Diff line change
Expand Up @@ -587,6 +587,21 @@ def test_path_without_leading_slash(self):
self.assertEqual(response.getheader("Location"),
self.tempdir_name + "/?hi=1")

def test_default_extension(self):
"""Checks an extensionless path finds a HMTL file, and finds an
extensionless file with priority.
"""
data1 = b"SPAM SPAM SPAM!\r\n"
with open(os.path.join(self.tempdir_name, 'spam.html'), 'wb') as f:
f.write(data1)
response = self.request(self.tempdir_name + '/spam')
self.check_status_and_reason(response, HTTPStatus.OK, data1)
data2 = b"The one true spam.\r\n"
with open(os.path.join(self.tempdir_name, 'spam'), 'wb') as f:
f.write(data2)
response = self.request(self.tempdir_name + '/spam')
self.check_status_and_reason(response, HTTPStatus.OK, data2)

def test_html_escape_filename(self):
filename = '<test&>.txt'
fullpath = os.path.join(self.tempdir, filename)
Expand Down