Apache · Configuration and operations

How do Apache virtual hosts work?

Easyvirtual hostshostingservernameUpdated Oct 2026
Quiz this track

Short answer

A virtual host groups configuration for a hostname or address. Apache selects one after the connection is accepted, mainly by the Host header for name-based hosting, and falls back to the first matching virtual host.

Name-based virtual hosting allows many domains on one IP address because HTTP carries the requested hostname in the Host header. IP-based virtual hosting still exists but is rarely needed. TLS complicates name-based hosting because the certificate is chosen before the encrypted request is read, which is why SNI exists.

apache
<VirtualHost *:80>
  ServerName example.com
  ServerAlias www.example.com
  DocumentRoot /var/www/example/public
  ErrorLog /var/log/apache2/example-error.log
  CustomLog /var/log/apache2/example-access.log combined
</VirtualHost>

<VirtualHost *:443>
  ServerName example.com
  ServerAlias www.example.com
  DocumentRoot /var/www/example/public
  SSLEngine on
  SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
  SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
</VirtualHost>

Selection and defaults

  • The first virtual host on a port is the default for unmatched requests
  • Always define an explicit default host, even if it only returns 404 or redirects
  • ServerName should be a canonical name; ServerAlias lists alternatives
  • apachectl -S prints the parsed virtual host map and the default host
  • Duplicate ServerName values across hosts produce a warning and ambiguous routing
A request with an unknown Host header lands on the default virtual host. If that host serves a real site, crawlers and scanners can reach it under arbitrary names, so make the default host harmless.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1What is the difference between name-based and IP-based virtual hosting?
  2. 2Which virtual host handles a request with an unknown Host header?
  3. 3How do you debug a virtual host that is not matching?
  4. 4How does SNI affect TLS virtual hosts?

Say it in the interview

A virtual host is a configuration container selected by address and hostname. Name-based hosting uses the Host header, and the first host on a port becomes the default. I always add an explicit catch-all default so unknown hostnames do not hit a real site. For TLS I rely on SNI and verify the mapping with apachectl -S.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Apache mock interview and get scored feedback on depth, clarity and confidence.