23.3. Serving Sites with Nginx
Nginx takes the edge role on web2: a static site over HTTPS, and - once Section 23.5 adds the application - the reverse proxy and PHP front end. Because this chapter publishes HTTPS from the first server block on, the certificates come first, built by a small script whose mechanics Section 23.4.1 explains in depth.
23.3.1. Server Blocks, Locations, and Static Content
Install the server on web2, as john, with sudo apt install
nginx. The package enables and starts Nginx with one default site
answering on port 80; the rest of this section replaces it. Debian's Nginx
reads /etc/nginx/nginx.conf, whose http block pulls in every
/etc/nginx/conf.d/*.conf file and every symlink in
/etc/nginx/sites-enabled/. Site files live in sites-available/
and are activated by symlinking them into sites-enabled/ - the
same available/enabled split Apache uses, managed by hand because
Nginx ships no a2ensite equivalent.
The static site needs a certificate before its server block can
load. Build the practice hierarchy on web1 - the host that owns the
lab's certificate material - and copy the files to web2 afterwards.
The script creates a self-signed root, an intermediate that is only
allowed to sign leaves, and three leaf certificates; it keeps every
private key at mode 0600 and writes a verification transcript. File
contents for web1, saved in the workspace as make-ca.sh:
#!/usr/bin/env bash
set -euo pipefail
dest="${1:?usage: make-ca.sh DESTINATION}"
umask 077
mkdir -p "$dest"
cd "$dest"
cat > root.cnf <<'CONF'
[req]
distinguished_name = dn
prompt = no
x509_extensions = v3_ca
[dn]
CN = Handbook Lab Root CA
O = Handbook Lab
[v3_ca]
basicConstraints = critical,CA:true
keyUsage = critical,keyCertSign,cRLSign
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always
CONF
cat > intermediate.cnf <<'CONF'
[req]
distinguished_name = dn
prompt = no
[dn]
CN = Handbook Lab Issuing CA
O = Handbook Lab
[v3_ca]
basicConstraints = critical,CA:true,pathlen:0
keyUsage = critical,keyCertSign,cRLSign
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always
CONF
cat > leaf.ext <<'CONF'
basicConstraints = critical,CA:false
keyUsage = critical,digitalSignature,keyEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @alt
[alt]
DNS.1 = placeholder.invalid
CONF
openssl req -x509 -newkey rsa:3072 -nodes -sha256 -days 3650 \
-config root.cnf -keyout root.key -out root.crt
openssl req -new -newkey rsa:3072 -nodes -sha256 \
-config intermediate.cnf -keyout intermediate.key -out intermediate.csr
openssl x509 -req -in intermediate.csr -CA root.crt -CAkey root.key \
-CAcreateserial -days 1825 -sha256 -extfile intermediate.cnf \
-extensions v3_ca -out intermediate.crt
make_leaf() {
local name="$1" cn="$2" san="$3"
openssl req -new -newkey rsa:2048 -nodes -sha256 \
-subj "/CN=$cn/O=Handbook Lab" -keyout "$name.key" -out "$name.csr"
{
printf '%s\n' \
'basicConstraints = critical,CA:false' \
'keyUsage = critical,digitalSignature,keyEncipherment' \
'extendedKeyUsage = serverAuth' \
'subjectAltName = @alt' \
'[alt]'
printf '%s\n' "$san"
} >"$name.ext"
openssl x509 -req -in "$name.csr" -CA intermediate.crt \
-CAkey intermediate.key -CAcreateserial -days 90 -sha256 \
-extfile "$name.ext" -out "$name.crt"
cat "$name.crt" intermediate.crt >"$name.fullchain.pem"
}
make_leaf www www.handbook.test 'DNS.1 = www.handbook.test
DNS.2 = handbook.test'
make_leaf shop shop.handbook.test 'DNS.1 = shop.handbook.test'
make_leaf wildcard '*.handbook.test' 'DNS.1 = *.handbook.test
DNS.2 = handbook.test'
{
echo 'leaf verification:'
openssl verify -CAfile root.crt -untrusted intermediate.crt www.crt shop.crt wildcard.crt
echo 'without the intermediate:'
openssl verify -CAfile root.crt www.crt || true
} >verify.txt 2>&1
chmod 0600 ./*.key
chmod 0644 ./*.crt ./*.pem ./*.cnf ./*.ext ./*.txt
Make it executable and run it, on web1, as john with the workspace as the working directory:
$ chmod 0755 make-ca.sh
The chmod is silent. Then run the script - it prints nothing of its
own, only OpenSSL's output: a long run of dot and plus characters
while each RSA key is generated, then a Certificate request
self-signature ok line and the subject for each certificate signed.
Selected output - the end of the run:
$ ./make-ca.sh ca
Certificate request self-signature ok
subject=CN=*.handbook.test, O=Handbook Lab
The script exits 0 and leaves its results in ca/. A hierarchy this
size has no revocation story - fine for a lab, inadequate for a
service other people depend on; running a private CA as a maintained
system, with renewal, revocation, and recovery procedures, is the
subject of Chapter 26. See exactly what was
produced, on web1, as john:
$ ls -l ca
total 104
-rw-r--r-- 1 john john 253 Nov 22 17:19 intermediate.cnf
-rw-r--r-- 1 john john 1582 Nov 22 17:19 intermediate.crt
-rw------- 1 john john 1289 Nov 22 17:19 intermediate.csr
-rw------- 1 john john 2484 Nov 22 17:19 intermediate.key
-rw------- 1 john john 41 Nov 22 17:19 intermediate.srl
-rw-r--r-- 1 john john 176 Nov 22 17:19 leaf.ext
-rw-r--r-- 1 john john 264 Nov 22 17:19 root.cnf
-rw-r--r-- 1 john john 1574 Nov 22 17:19 root.crt
-rw------- 1 john john 2484 Nov 22 17:19 root.key
-rw------- 1 john john 41 Nov 22 17:19 root.srl
-rw-r--r-- 1 john john 1472 Nov 22 17:19 shop.crt
-rw------- 1 john john 936 Nov 22 17:19 shop.csr
-rw------- 1 john john 175 Nov 22 17:19 shop.ext
-rw-r--r-- 1 john john 3054 Nov 22 17:19 shop.fullchain.pem
-rw------- 1 john john 1704 Nov 22 17:19 shop.key
-rw-r--r-- 1 john john 226 Nov 22 17:19 verify.txt
-rw-r--r-- 1 john john 1484 Nov 22 17:19 wildcard.crt
-rw------- 1 john john 932 Nov 22 17:19 wildcard.csr
-rw------- 1 john john 194 Nov 22 17:19 wildcard.ext
-rw-r--r-- 1 john john 3066 Nov 22 17:19 wildcard.fullchain.pem
-rw------- 1 john john 1704 Nov 22 17:19 wildcard.key
-rw-r--r-- 1 john john 1489 Nov 22 17:19 www.crt
-rw------- 1 john john 932 Nov 22 17:19 www.csr
-rw------- 1 john john 196 Nov 22 17:19 www.ext
-rw-r--r-- 1 john john 3071 Nov 22 17:19 www.fullchain.pem
-rw------- 1 john john 1700 Nov 22 17:19 www.key
Three leaf names were issued: www, used on web1 from
Section 23.4.1; shop, likewise; and the wildcard for
*.handbook.test, used on web2 here. Each *.fullchain.pem is the
leaf followed by the intermediate in one file - exactly what a server
should present. Every .key is 0600; the .csr and .srl working
files inherit the same protection from the script's umask 077.
Copy the files the two other hosts need - on the practice network,
copy intermediate.crt, wildcard.crt, wildcard.fullchain.pem,
and wildcard.key from web1's workspace to web2, and root.crt into
the ca/ directory of client1's workspace - with whatever transfer
method your hosts share:
scp as covered in Chapter 20, or any of
Chapter 21's services. On web2, as
john:
$ sudo install -m 0644 ~/debian-handbook/web-services/ca/intermediate.crt /etc/ssl/certs/handbook-intermediate.crt
$ sudo install -m 0644 ~/debian-handbook/web-services/ca/wildcard.fullchain.pem /etc/ssl/certs/handbook-wildcard.fullchain.pem
$ sudo install -m 0640 -g www-data ~/debian-handbook/web-services/ca/wildcard.key /etc/ssl/private/handbook-wildcard.key
All three are silent. The certificate and chain are world-readable in
/etc/ssl/certs; the key is root-owned, group-readable only by
www-data, in /etc/ssl/private - Section 23.4.1 examines those
permissions and why they are exactly this shape.
client1 must trust the lab's root before any HTTPS check can pass.
With root.crt in the workspace's ca/ directory, on client1, as
john:
$ sudo install -m 0644 ~/debian-handbook/web-services/ca/root.crt /usr/local/share/ca-certificates/handbook-lab-root.crt
$ sudo update-ca-certificates
Updating certificates in /etc/ssl/certs...
rehash: warning: skipping ca-certificates.crt, it does not contain exactly one certificate or CRL
1 added, 0 removed; done.
Running hooks in /etc/ca-certificates/update.d...
done.
The rehash: line is a harmless notice from the hash-symlink step
about the concatenated bundle file; the count is what matters - one
certificate was added to the system trust store, and curl, openssl,
and Python now verify the lab hierarchy through it.
Section 23.7.1 covers withdrawing trust again.
The static site writes one log line per request with a request
identifier, which needs a custom log_format defined before the site
references it. File contents for web2, saved in the workspace as
fixtures/nginx/log-format.conf:
log_format handbook '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" "$http_user_agent" '
'rid=$request_id';
And the site itself - file contents for web2,
fixtures/nginx/static.conf:
server {
listen 80;
server_name static.handbook.test;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
http2 on;
server_name static.handbook.test;
ssl_certificate /etc/ssl/certs/handbook-wildcard.fullchain.pem;
ssl_certificate_key /etc/ssl/private/handbook-wildcard.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers off;
add_header Strict-Transport-Security "max-age=31536000" always;
root /var/www/static.handbook.test;
index index.html;
client_max_body_size 1m;
error_page 404 /404.html;
location = /404.html {
internal;
}
location / {
try_files $uri $uri/ =404;
}
access_log /var/log/nginx/static.access.log handbook;
error_log /var/log/nginx/static.error.log;
}
Two server blocks share the name: the first owns plain HTTP and
does nothing but redirect, exactly like Apache's www site; the second
owns the TLS listener. ssl_certificate points at the fullchain
file, so Nginx presents the leaf and the intermediate together
without a separate chain directive. http2 on enables HTTP/2 for
clients that offer it. client_max_body_size 1m and the error-page
plumbing are exercised in Section 23.3.3; the TLS directives are
discussed with the rest of the policy in Section 23.4.4.
Content files - fixtures/static/nginx-index.html:
<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<title>Nginx static site</title></head>
<body><h1>static.handbook.test</h1>
<p>Static content served by Nginx.</p>
</body></html>
And fixtures/static/nginx-404.html:
<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<title>Not found</title></head>
<body><h1>Not found</h1>
<p>The requested path does not exist on this site.</p>
</body></html>
Install content, configuration, and activation, on web2, as john:
$ sudo install -d -o www-data -g www-data /var/www/static.handbook.test
$ sudo install -m 0644 -o www-data -g www-data fixtures/static/nginx-index.html /var/www/static.handbook.test/index.html
$ sudo install -m 0644 -o www-data -g www-data fixtures/static/nginx-404.html /var/www/static.handbook.test/404.html
$ sudo install -m 0644 fixtures/nginx/log-format.conf /etc/nginx/conf.d/handbook-log.conf
$ sudo install -m 0644 fixtures/nginx/static.conf /etc/nginx/sites-available/static.handbook.test.conf
$ sudo rm /etc/nginx/sites-enabled/default
$ sudo ln -sfn /etc/nginx/sites-available/static.handbook.test.conf /etc/nginx/sites-enabled/static.handbook.test.conf
Every command above is silent. Validate and activate:
$ sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
$ sudo systemctl restart nginx
The restart prints nothing; Nginx re-reads its configuration and the
listeners change. The nginx binary's own flags:
| Option | Description |
|---|---|
-t |
parse and test the configuration without applying it; the gate before every reload |
-T |
test, then dump the fully expanded configuration - the includes resolved - to the terminal |
-v |
print the version |
-V |
print the version, build options, and compile-time paths |
Verify from the client. On client1, as john:
$ curl -sS https://static.handbook.test/
<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<title>Nginx static site</title></head>
<body><h1>static.handbook.test</h1>
<p>Static content served by Nginx.</p>
</body></html>
The request resolved through the lab resolver, validated the wildcard certificate against the trust root installed a moment ago, and was served over HTTP/2. Confirm what the edge now listens on - on web2, as john:
$ sudo ss -ltnp
State Recv-Q Send-Q Local Address:Port Peer Address:PortProcess
LISTEN 0 511 0.0.0.0:80 0.0.0.0:* users:(("nginx",pid=15338,fd=11),("nginx",pid=15337,fd=11))
LISTEN 0 128 0.0.0.0:22 0.0.0.0:* users:(("sshd",pid=816,fd=6))
LISTEN 0 511 0.0.0.0:443 0.0.0.0:* users:(("nginx",pid=15338,fd=12),("nginx",pid=15337,fd=12))
LISTEN 0 128 [::]:22 [::]:* users:(("sshd",pid=816,fd=7))
Two Nginx processes hold both web ports: one master and one worker.
The flags, all composable: -l listening sockets only, -t TCP,
-n numeric addresses and ports, -p show the owning process
(Chapter 17 uses the same tool). No
backend port appears because none is served by this host - exactly
the allocation planned in Section 23.1.3.
23.3.2. Configuration Includes and Site Activation
Nginx's configuration is a tree of includes that flattens at load
time. Debian's nginx.conf defines process behavior and one http
block; inside it, include /etc/nginx/conf.d/*.conf; pulls in
cross-site settings like the handbook log format, and
include /etc/nginx/sites-enabled/*; pulls in one file per site.
Three conventions fall out of that structure:
- One file per site, named for the site.
static.handbook.test.confcontains only that name's server blocks; nothing else in the tree changes when a site is edited. - Activation is a symlink.
ln -sfnfromsites-enabled/to the file insites-available/; remove the symlink and the site is gone, with the source file kept for the next change. The pattern is identical to Apache's, so the mental model from Section 23.2 transfers directly. - Shared snippets live in
snippets/. Debian ships tested include files there - Section 23.5.4 usessnippets/fastcgi-php.confrather than hand-writing the FastCGI parameters.
When a site misbehaves and the reason is not in its own file,
sudo nginx -T dumps the fully resolved configuration - every
include expanded - so you can see exactly what the master process
will load. Each site's access_log and error_log directives keep
per-site files under /var/log/nginx/, so a single host can host
many sites without interleaving their traffic; the custom handbook
format appends rid=$request_id, which Section 23.6.1 uses to follow
one request across two logs.
23.3.3. Request Limits, Error Handling, and Configuration Tests
Three edge behaviors are worth exercising on a site you control before a real user finds them.
Body size limit. client_max_body_size 1m rejects any request
body over one megabyte before it consumes the worker's time - the
answer is 413, not an error after a long upload. Create an oversized
body in the workspace, on client1, as john:
$ head -c 2000000 /dev/zero > upload.bin
The redirection writes the file silently; nothing appears in the terminal. Send it:
$ curl -sS -o /dev/null -w '%{http_code}\n' --data-binary @upload.bin https://static.handbook.test/
413
Custom error pages. Without configuration, a missing path
returns Nginx's built-in 404 page. The static site overrides that:
error_page 404 /404.html plus an internal location means the
custom page is served for errors but cannot be fetched directly.
Check both the status and the body, on client1, as john:
$ curl -sS -o /dev/null -w '%{http_code}\n' https://static.handbook.test/missing
404
$ curl -sS https://static.handbook.test/missing
<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<title>Not found</title></head>
<body><h1>Not found</h1>
<p>The requested path does not exist on this site.</p>
</body></html>
Remove the practice upload again, on client1, as john:
$ rm upload.bin
Silent, and the workspace is back to holding only its real files.
Configuration tests on a broken site. Nginx refuses to load a
configuration it cannot parse, and nginx -t catches the problem
before a reload attempts it. File contents for web2, saved in the
workspace as nginx-fixtures/bad.conf:
server {
listen 80;
server_name bad.handbook.test;
this_is_not_an_nginx_directive on;
}
Install, enable, and test - on web2, as john. The first two commands are silent; the third is the point of the exercise:
$ sudo install -m 0644 nginx-fixtures/bad.conf /etc/nginx/sites-available/bad.handbook.test.conf
$ sudo ln -sfn /etc/nginx/sites-available/bad.handbook.test.conf /etc/nginx/sites-enabled/bad.handbook.test.conf
$ sudo nginx -t
2026/11/22 17:03:52 [emerg] 15557#15557: unknown directive "this_is_not_an_nginx_directive" in /etc/nginx/sites-enabled/bad.handbook.test.conf:4
nginx: configuration file /etc/nginx/nginx.conf test failed
The failure names the directive, the file, and the line, and the command exits nonzero. A reload at this point would fail without changing the running workers - but, as with Apache, the safe habit is to test first and reload only after a pass. Undo the damage:
$ sudo rm -f /etc/nginx/sites-enabled/bad.handbook.test.conf
$ sudo rm -f /etc/nginx/sites-available/bad.handbook.test.conf
$ sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
Reload to make the running master re-read the (again valid) tree:
$ sudo systemctl reload nginx
$ sudo systemctl is-active nginx
active
The reload itself prints nothing. Like Apache's, Nginx's master process re-reads the configuration, starts new workers, and lets the old ones finish their open requests; clients see no gap.