Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Validate Headers

Now that you can parse headers, let’s implement a strict rule from the HTTP/1.1 specification.

In the early days of the web (HTTP/1.0), a server assumed that any connection to its IP address was meant for the one and only website it hosted. But as the web grew, servers started hosting multiple websites on the same IP address (a technique called Virtual Hosting).

To make Virtual Hosting possible, HTTP/1.1 introduced the mandatory Host header. The client uses this header to tell the server which website they are trying to reach.

The Strict RFC Requirement

According to RFC 9112 Section 3.2:

A client MUST send a Host header field in all HTTP/1.1 request messages. A server MUST respond with a 400 (Bad Request) status code to any HTTP/1.1 request message that lacks a Host header field.

This is not optional; it is a fundamental security and routing requirement for modern HTTP!

Your Task

Inspect the headers of the incoming request.

  • If the Host header is missing entirely, you MUST respond with 400 Bad Request.
  • If the Host header is present (with any value), respond with 200 OK.

Important

Run the below docker command to test your solution.

docker run \
  --rm \
  --add-host host.docker.internal:host-gateway \
  codeberg.org/level0/buildit/http-server:latest \
  --addr host.docker.internal:8080 \
  --until headers_validation