A single Apache server hosting one site is the textbook case. The reality on most boxes we inherit is four to forty vhosts, each with its own DocumentRoot, log file, and rewrite quirks — and somewhere in there is a “catch-all” config that grew over a weekend and now answers requests no one remembers configuring. This article is the vhost pattern we use for new installs and the cleanup we apply when we take over an old one.
How to verify
Start by asking the running daemon what it actually thinks the vhost map looks like. Edited files do not matter — what matters is what is loaded:
sudo apache2ctl -S
sudo apache2ctl -D DUMP_VHOSTS
ls -la /etc/apache2/sites-enabled/
sudo apache2ctl configtest
apache2ctl -S prints the listening sockets and, for each one, every name-based vhost in the order they were parsed. The first vhost on a given IP:port is the implicit default — the one that catches requests with no matching ServerName. Confirm that the implicit default is the file you intended, not whatever happened to sort first alphabetically.
What’s happening
Apache resolves an incoming HTTP request to a vhost in two steps. First it matches the connection’s local IP and port to a <VirtualHost IP:port> block. Second, within the set of vhosts on that socket, it matches the request’s Host: header against each vhost’s ServerName and ServerAlias directives. If nothing matches, the first vhost on that socket wins.
That fallback is the trap. A misspelled ServerName or a forgotten *:80 block silently routes traffic to the wrong site, often delivering one site’s content under another site’s hostname. The fix is to define an explicit catch-all vhost first in the load order, so unknown hostnames hit a 404 or a 301 to the canonical site rather than leaking a real site’s content.
The directives that matter inside a vhost:
ServerName— the canonical hostname. Exactly one.ServerAlias— additional hostnames that should serve the same site. Wildcards allowed.DocumentRoot— the filesystem path mapped to/.<Directory>— per-directory rules (AllowOverride, Require, Options).ErrorLogandCustomLog— per-vhost logs.RewriteEngine Onplus per-vhost rewrites.
Per-vhost logs are the single highest-leverage habit. With one access log per vhost, GoAccess, awk, or grep give per-site numbers in seconds; with a shared log, you fight the format every time.
The procedure
-
Create the DocumentRoot. Owned by
www-data:www-dataif the app reads/writes as the Apache user; owned by an app user withwww-datagroup access if PHP-FPM runs under its own pool:sudo mkdir -p /var/www/example.com/public sudo chown -R www-data:www-data /var/www/example.com sudo find /var/www/example.com -type d -exec chmod 750 {} \; sudo find /var/www/example.com -type f -exec chmod 640 {} \; -
Write the vhost file. Save as
/etc/apache2/sites-available/example.com.conf:<VirtualHost *:80> ServerName example.com ServerAlias www.example.com DocumentRoot /var/www/example.com/public ErrorLog ${APACHE_LOG_DIR}/example.com-error.log CustomLog ${APACHE_LOG_DIR}/example.com-access.log combined <Directory /var/www/example.com/public> Options -Indexes +FollowSymLinks AllowOverride None Require all granted </Directory> # Static asset cache headers <FilesMatch "\.(css|js|woff2|png|jpg|svg)$"> Header set Cache-Control "public, max-age=2592000, immutable" </FilesMatch> </VirtualHost>AllowOverride Noneis the default we recommend —.htaccessparsing is a measurable per-request cost, and the rules belong in the vhost where they are reviewable. See .htaccess pitfalls for the long argument. -
Add a catch-all default. Save as
/etc/apache2/sites-available/000-catchall.conf. The numeric prefix forces it to load first:<VirtualHost *:80> ServerName catchall.invalid DocumentRoot /var/www/catchall <Directory /var/www/catchall> Require all denied </Directory> ErrorLog ${APACHE_LOG_DIR}/catchall-error.log CustomLog ${APACHE_LOG_DIR}/catchall-access.log combined </VirtualHost>Any request whose
Host:header does not match a realServerNamelands here and gets a 403. The catch-all access log becomes your “who is scanning us with bogus hostnames” feed. -
Enable, test, reload. Test before reload — Apache will refuse to reload on a config error, but the test surfaces the line number:
sudo a2ensite 000-catchall.conf example.com.conf sudo apache2ctl configtest sudo systemctl reload apache2 -
Verify the vhost map matches your intent. Re-run
apache2ctl -Sand confirm the catch-all is the first entry under*:80, with each real site listed below it. A discrepancy here is the bug, not the symptom. -
Set up a parallel HTTPS vhost. Most sites need both 80 and 443 vhosts. The 80 vhost should redirect to 443 once the cert is in place — see Apache + Let’s Encrypt with certbot for the cert provisioning step. The 443 vhost mirrors the 80 vhost’s structure with
SSLCertificateFile/SSLCertificateKeyFiledirectives added.
Common pitfalls
- A trailing slash mismatch between
ServerAlias www.example.comand DNS pointing bothwwwand apex at the same IP can produce a redirect loop when the vhost contains aRedirect / https://example.com/rule that fires for both names. - Per-vhost
ErrorLogpaths must exist before the daemon starts — Apache creates the file but not the directory; if you log to/var/log/apache2/sites/example.com/error.log, mkdir the directory first. ServerNamewithout a port is fine for the default 80/443; if the vhost listens on a non-standard port, writeServerName example.com:8080or external links generated by Apache will be wrong.- Wildcard
ServerAlias *.example.commatches one label only —a.example.comworks,a.b.example.comdoes not. For nested wildcards, list them explicitly or use a<VirtualHost>withUseCanonicalName Offand an internal redirect. - Reloading does not always reload module config — adding
mod_sslto a previously HTTP-only daemon requiressystemctl restart apache2, notreload.journalctl -u apache2shows the difference.
Stack Harbor manages Apache fleets where the vhost layout is config-managed, the catch-all is mandatory, and per-vhost logs flow into a single search index. If your inherited vhost directory has 30 files and nobody knows which sites are live, that audit is part of the standard work we do under Managed Operations.