Add Custom Response Headers in http.server in Python 3.15

Add Custom Response Headers in http.server in Python 3.15

The http.server module is a convenient way to serve a directory over HTTP during development. Its responses carry a fixed set of headers describing the server, the date and the file being returned. Adding custom headers required subclassing SimpleHTTPRequestHandler and overriding end_headers.

Before Python 3.15, serving a directory produced only the built-in headers:

python -m http.server 8000
curl -I http://127.0.0.1:8000
HTTP/1.0 200 OK
Server: SimpleHTTP/0.6 Python/3.14.10
Date: Mon, 02 Nov 2026 05:38:40 GMT
Content-type: text/html; charset=utf-8
Content-Length: 876

Since Python 3.15, the --header (or -H) option adds a header to the response:

python -m http.server 8000 --header Cache-Control no-store
HTTP/1.0 200 OK
Server: SimpleHTTP Python/3.15.2
Date: Mon, 02 Nov 2026 05:38:40 GMT
Content-type: text/html; charset=utf-8
Content-Length: 876
Cache-Control: no-store

The header name and its value are given as two separate arguments rather than a single Name: value string, which differs from the convention used by tools such as curl. The option can be repeated to send more than one header:

python -m http.server 8000 --header Cache-Control no-store --header Access-Control-Allow-Origin '*'

The same headers can be set from Python with extra_response_headers argument of SimpleHTTPRequestHandler:

import functools
import http.server
import socketserver

handler = functools.partial(
    http.server.SimpleHTTPRequestHandler,
    extra_response_headers=[
        ('Cache-Control', 'no-store'),
        ('Access-Control-Allow-Origin', '*'),
    ],
)

with socketserver.TCPServer(('', 8000), handler) as httpd:
    httpd.serve_forever()

The argument is keyword-only and takes a sequence of name and value pairs. The functools.partial function is used because the server creates a new handler for every request, so the value has to be supplied in advance rather than by instantiating the handler directly.

The headers are added to successful HTTP 200 responses only, so a 404 carries none of them. Headers that the server generates itself, such as Content-Type, are never overwritten by the ones supplied here.

Leave a Comment

Cancel reply

Your email address will not be published.