Skip to content

Apache virtual hosts that hold up in production

How to build name-based Apache vhosts that survive real traffic — per-site logs, per-vhost limits, a sane default catch-all, and a config layout you can hand off.

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).
  • ErrorLog and CustomLog — per-vhost logs.
  • RewriteEngine On plus 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

  1. Create the DocumentRoot. Owned by www-data:www-data if the app reads/writes as the Apache user; owned by an app user with www-data group 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 {} \;
  2. 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 None is the default we recommend — .htaccess parsing is a measurable per-request cost, and the rules belong in the vhost where they are reviewable. See .htaccess pitfalls for the long argument.

  3. 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 real ServerName lands here and gets a 403. The catch-all access log becomes your “who is scanning us with bogus hostnames” feed.

  4. 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
  5. Verify the vhost map matches your intent. Re-run apache2ctl -S and 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.

  6. 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 / SSLCertificateKeyFile directives added.

Common pitfalls

  • A trailing slash mismatch between ServerAlias www.example.com and DNS pointing both www and apex at the same IP can produce a redirect loop when the vhost contains a Redirect / https://example.com/ rule that fires for both names.
  • Per-vhost ErrorLog paths 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.
  • ServerName without a port is fine for the default 80/443; if the vhost listens on a non-standard port, write ServerName example.com:8080 or external links generated by Apache will be wrong.
  • Wildcard ServerAlias *.example.com matches one label only — a.example.com works, a.b.example.com does not. For nested wildcards, list them explicitly or use a <VirtualHost> with UseCanonicalName Off and an internal redirect.
  • Reloading does not always reload module config — adding mod_ssl to a previously HTTP-only daemon requires systemctl restart apache2, not reload. journalctl -u apache2 shows 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.