23.2. Serving Sites with Apache

This section builds two name-based sites on web1: www.handbook.test, which exists to redirect everything to HTTPS, and shop.handbook.test, which serves content. Along the way it covers Debian's site and module layout, directory access rules, configuration validation, and the reload that activates changes without dropping requests.

23.2.1. Packages, Modules, and Debian Site Configuration

Install the server on web1, as john, with sudo apt install apache2. apt resolves the dependencies and asks for confirmation in the usual interactive prompt (Chapter 6); the package starts the service immediately with one default site serving /var/www/html on port 80.

Debian's Apache reads /etc/apache2/apache2.conf, which in turn pulls in four directories rather than one monolithic file:

  • mods-available/ and mods-enabled/ - one .load (and optionally .conf) file per module; enabling a module is a symlink into mods-enabled/.
  • sites-available/ and sites-enabled/ - one file per virtual host; the shipped 000-default.conf is the enabled default site.
  • conf-available/ and conf-enabled/ - server-wide snippets such as security headers.
  • ports.conf - the Listen directives for 80 and 443.

The available/enabled split means every piece of configuration exists as a file you can read and edit, and activation is a symlink you can see. Debian ships a small family of tools that manage exactly those symlinks:

Tool Manages Effect
a2enmod name mods-enabled/ enables a module; resolves module dependencies
a2dismod name mods-enabled/ disables a module
a2ensite name sites-enabled/ enables a virtual host file
a2dissite name sites-enabled/ disables a virtual host file
a2enconf name conf-enabled/ enables a global configuration snippet
a2disconf name conf-enabled/ disables a global snippet

Each of them prints what it did and the reminder that a reload activates the change.

Two snippets of global configuration make the practice host behave. The first gives Apache a server-wide name - without one, every start logs a warning about guessing the fully qualified domain name - and the second keeps the server from advertising its version. File contents for web1, saved in the workspace as fixtures/apache/handbook.conf:

ServerName web1.handbook.test
ServerTokens Prod
ServerSignature Off

Install and enable it, on web1, as john:

$ sudo install -m 0644 fixtures/apache/handbook.conf /etc/apache2/conf-available/handbook.conf
$ sudo a2enconf handbook

The install is silent; a2enconf prints Enabling conf handbook. followed by the standard reload reminder, in the same format as the site enable shown in Section 23.2.2.

The sites in the rest of this chapter need three modules: ssl for the HTTPS listeners of Section 23.4, headers to set Strict-Transport-Security, and rewrite, which many packaged applications expect. Enable them, on web1, as john:

$ sudo a2enmod ssl headers rewrite
Considering dependency mime for ssl:
Module mime already enabled
Considering dependency socache_shmcb for ssl:
Module socache_shmcb already enabled
Enabling module ssl.
See /usr/share/doc/apache2/README.Debian.gz on how to configure SSL and create self-signed certificates.
Enabling module headers.
Enabling module rewrite.
To activate the new configuration, you need to run:
  systemctl restart apache2

On a host where a dependency is not yet enabled, the Considering dependency ... lines say Enabling module ... instead of already enabled; the tool resolves what it needs. Confirm what is loaded, with the same privilege:

$ sudo apache2ctl -M | grep -E "ssl|headers|rewrite"
 headers_module (shared)
 rewrite_module (shared)
 ssl_module (shared)

The -M flag lists every loaded module, static and shared; the pipeline filters it to the three of interest. apache2ctl is Apache's administrative front end:

Option Description
configtest parses the full configuration and reports syntax errors; run before every reload
-M lists loaded modules
-S shows the virtual host map - which vhost matches which name and port; useful when a site serves the wrong content
-V prints version, MPM, and compile-time paths

23.2.2. Name-Based Virtual Hosts and Document Roots

Name-based hosting means several sites share one address, and Apache picks between them with the Host header the client sends (or the SNI name on a TLS connection). The first enabled vhost for a port is the default: it answers names no other vhost claims, which is why the shipped 000-default catches stray requests until you replace it.

Each site gets a document root named after itself, so file paths and URLs stay obvious. The content files are minimal HTML - file contents for web1, saved in the workspace as fixtures/static/www-index.html:

<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<title>Apache www site</title></head>
<body><h1>www.handbook.test</h1>
<p>Static content served by Apache HTTP Server.</p>
</body></html>

And fixtures/static/shop-index.html:

<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<title>Apache shop site</title></head>
<body><h1>shop.handbook.test</h1>
<p>Second name-based virtual host on the same address.</p>
</body></html>

Create the roots with www-data ownership and install the content, on web1, as john:

$ sudo install -d -o www-data -g www-data /var/www/www.handbook.test /var/www/shop.handbook.test
$ sudo install -m 0644 -o www-data -g www-data fixtures/static/www-index.html /var/www/www.handbook.test/index.html
$ sudo install -m 0644 -o www-data -g www-data fixtures/static/shop-index.html /var/www/shop.handbook.test/index.html

All three commands are silent on success. The site for www.handbook.test does nothing but redirect - every request, of every depth, moves to HTTPS; Section 23.4 gives the redirect its target. File contents for web1, fixtures/apache/www.conf:

<VirtualHost *:80>
    ServerName www.handbook.test
    ServerAlias handbook.test
    Redirect permanent / https://www.handbook.test/
    ErrorLog ${APACHE_LOG_DIR}/www-error.log
    CustomLog ${APACHE_LOG_DIR}/www-access.log combined
</VirtualHost>

ServerAlias handbook.test makes the bare domain behave like the www name. Redirect permanent / https://www.handbook.test/ sends a 301 for the whole path space; the client repeats the request against the HTTPS site. Each vhost keeps its own logs: APACHE_LOG_DIR comes from /etc/apache2/envvars and is /var/log/apache2.

The shop site serves content instead of redirecting, and it demonstrates the two policy tools this section relies on: a Directory block granting access to the root, and a nested block taking it away for a private subdirectory. File contents for web1, fixtures/apache/shop.conf:

<VirtualHost *:80>
    ServerName shop.handbook.test
    DocumentRoot /var/www/shop.handbook.test

    <Directory /var/www/shop.handbook.test>
        Options -Indexes +FollowSymLinks
        AllowOverride None
        Require all granted
    </Directory>

    <Directory /var/www/shop.handbook.test/private>
        Require all denied
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/shop-error.log
    CustomLog ${APACHE_LOG_DIR}/shop-access.log combined
</VirtualHost>

Create the private directory and a file in it, on web1, as john:

$ sudo install -d -o www-data -g www-data /var/www/shop.handbook.test/private
$ printf 'internal shop material\n' | sudo tee /var/www/shop.handbook.test/private/secret.txt > /dev/null

tee writes the line to the file as root; the redirect to /dev/null keeps the terminal clean because tee also echoes its input, and the command itself prints nothing here. Give the file ordinary content permissions:

$ sudo chown www-data:www-data /var/www/shop.handbook.test/private/secret.txt && sudo chmod 0644 /var/www/shop.handbook.test/private/secret.txt

Also silent. Install both site files, disable the shipped default, and enable the new sites:

$ sudo install -m 0644 fixtures/apache/www.conf /etc/apache2/sites-available/www.conf
$ sudo install -m 0644 fixtures/apache/shop.conf /etc/apache2/sites-available/shop.conf
$ sudo a2dissite 000-default

a2dissite prints Site 000-default disabled. plus the reload reminder, in the same format as the captured disable in Section 23.2.3.

$ sudo a2ensite www shop
Enabling site www.
Enabling site shop.
To activate the new configuration, you need to run:
  systemctl reload apache2

Nothing is live yet - the running workers still hold the old configuration. Validate before activating, on web1, as john:

$ sudo apache2ctl configtest
Syntax OK

The check parses everything Apache would load, including both new sites, and prints Syntax OK when it accepts the whole set; anything else means the reload must not happen yet. Activation follows in Section 23.2.4.

23.2.3. Directory Access, Ownership, and Configuration Validation

Debian's default Apache denies access to the whole filesystem and grants it back piece by piece through Directory blocks; a vhost whose DocumentRoot has no grant serves 403 instead of content. The shop site's outer block is the grant:

  • Require all granted - any client may fetch.
  • Require all denied in the nested block - no client may fetch, and inner blocks win over outer ones, so /private is dark even though its parent is open. Section 23.4.1 verifies the denial over HTTPS once the TLS listener exists.
  • Options -Indexes +FollowSymLinks - turn off automatic directory listings (a missing index.html then returns 403 rather than a file list) while letting the server follow symlinks inside the root.
  • AllowOverride None - ignore .htaccess files entirely. Apache supports per-directory override files, and some packaged applications require them, but they are evaluated per request and hide policy from the main configuration; on a host you control end to end, keep policy in the vhost.

Ownership of served content is deliberately boring. Check what the shop's front page actually is, on web1, as john:

$ stat -c '%U:%G %a %n' /var/www/shop.handbook.test/index.html
www-data:www-data 644 /var/www/shop.handbook.test/index.html

The stat -c format verbs - %U/%G owner and group, %a octal mode, %n name - are the ones Chapter 5 introduces. The file belongs to www-data, mode 644: the server account can read it (and so can everyone else, which is fine for public content - the data itself must not be secret, only correct). An alternative that works just as well is root-owned content that the server only reads; choose one policy per site and apply it uniformly. The one ownership that is always wrong for public content is making it writable by the server account when nothing needs to write it.

Configuration validation deserves a deliberate failure, because the safe workflow is validate → reload, and the interesting question is what a rejected configuration looks like. File contents for web1, fixtures/apache/broken.conf:

<VirtualHost *:80>
    ServerName broken.handbook.test
    DocumentRoot /var/www/broken.handbook.test
    ThisIsNotAnApacheDirective on
</VirtualHost>

Save it, install it, enable it, and test again - on web1, as john. The install is silent; the next two commands are not:

$ sudo install -m 0644 fixtures/apache/broken.conf /etc/apache2/sites-available/broken.conf
$ sudo a2ensite broken
Enabling site broken.
To activate the new configuration, you need to run:
  systemctl reload apache2
$ sudo apache2ctl configtest
AH00112: Warning: DocumentRoot [/var/www/broken.handbook.test] does not exist
AH00526: Syntax error on line 4 of /etc/apache2/sites-enabled/broken.conf:
Invalid command 'ThisIsNotAnApacheDirective', perhaps misspelled or defined by a module not included in the server configuration

The command exits with status 1. Two different findings are visible: the missing DocumentRoot is only a warning (the site would serve 404s), while the unknown directive is a syntax error that stops the whole configuration from loading. The two activation verbs would fail differently with this file enabled: a restart would refuse to come up at all, while a reload would quietly leave the old workers serving the old configuration - the running service and the files on disk silently diverging. That divergence is exactly why the test comes first. Disable the site and confirm recovery:

$ sudo a2dissite broken
Site broken disabled.
To activate the new configuration, you need to run:
  systemctl reload apache2
$ sudo apache2ctl configtest
Syntax OK

The broken file is still in sites-available/; that directory is storage, not policy, and only sites-enabled/ decides what loads. When an Invalid command error names a real directive rather than a typo, the usual cause is a missing module - enable it with a2enmod and test again.

23.2.4. Enabling Sites and Reloading Without Interrupting Requests

Activation is a reload, not a restart. systemctl reload apache2 sends the master process a graceful signal: the master re-reads its configuration, starts new workers with it, and lets the old workers finish every request they already hold before they exit. A restart, by contrast, discards workers immediately and aborts whatever they were doing. On web1, as john:

$ sudo systemctl reload apache2

The command returns silently; a reload normally prints nothing. Confirm the unit is healthy afterwards:

$ sudo systemctl is-active apache2
active

Now verify from the client that both sites behave. On client1, as john:

$ curl -sS http://shop.handbook.test/
<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<title>Apache shop site</title></head>
<body><h1>shop.handbook.test</h1>
<p>Second name-based virtual host on the same address.</p>
</body></html>

The same address, the same port, and the name in the request decided which site answered. The www name answers with a redirect:

$ curl -sS -o /dev/null -w '%{http_code} %{redirect_url}\n' http://www.handbook.test/
301 https://www.handbook.test/

No body was printed because -o /dev/null discarded it; the -w write-out reported the status and the location Apache sent. curl is used this way throughout the chapter:

Option Description
-sS silent progress bar, but show errors if they occur
-o file write the body to a file instead of the terminal
-w format after the transfer, print the given variables, e.g. %{http_code}, %{redirect_url}, %{time_total}
-I request headers only and print them
-H 'Header: value' send an extra request header
--max-time seconds give up after the given time; used against deliberately stalled backends
--unix-socket path connect to a Unix socket instead of TCP

A reload does not drop in-flight requests; Apache finishes them on the old workers while new ones already use the new configuration. That property is what makes validate → reload a safe routine, and it holds for the worker-model change of Section 23.3 equally: always configtest first, reload second, and treat any request errors during the window as a bug to investigate, not an acceptable loss.