How Does Apache Select a Virtual Host for a Request?

When a web server receives an incoming HTTP request, it must quickly determine which website or application should handle it. Apache HTTP Server manages this process through a specific resolution algorithm that evaluates IP addresses, port numbers, and the HTTP request headers. This article breaks down how Apache processes these incoming requests, differentiates between IP-based and name-based virtual hosts, and selects the final configuration to serve the content.

Step 1: Matching IP Address and Port Number

The very first thing Apache does when a connection is established is look at the destination IP address and port number of the request. Apache compares this data against the VirtualHost directives configured in your server files (e.g., <VirtualHost 192.168.1.1:80> or <VirtualHost *:80>).

Step 2: Evaluating the Host Header (Name-Based Resolution)

If multiple virtual hosts match the IP address and port (which is the most common scenario for modern servers using wildcard * blocks), Apache must narrow it down using the HTTP request itself. It looks directly at the Host: header sent by the client’s browser.

Apache then scans the matching virtual host blocks for two specific directives:

  1. ServerName: The primary domain name assigned to the virtual host (e.g., example.com).
  2. ServerAlias: Additional domain names or subdomains that should match the same block (e.g., www.example.com or *.example.com).

Apache will serve the request using the virtual host where the ServerName or ServerAlias exactly matches the domain in the Host: header.

Step 3: Falling Back to the Default Virtual Host

What happens if the browser requests a domain name that isn’t explicitly listed in any ServerName or ServerAlias configuration, or if the Host: header is missing entirely?

Apache does not return an error. Instead, it falls back to a default configuration:

The Default Rule: Apache will automatically route the request to the first virtual host listed in its configuration files that matches the IP address and port.

Because Apache loads configuration files in alphabetical order (typically from directories like sites-enabled/), the file that is loaded first acts as the catch-all safety net for any unmatched traffic.