Sub topic 3
Nginx basics: server blocks, root, and locations
This chapter assumes you can edit files as root on a Debian or Ubuntu server, have Nginx installed from the distribution package, and can read an HTTP request line and Host header. By the end you should be able to predict which server block and which location block handle any given request, and where on disk Nginx looks for the file.
How the configuration is organized
Nginx reads one main file, /etc/nginx/nginx.conf. Directives live inside nested blocks called contexts:
- main: the top level, with process-wide settings such as
userandworker_processes. - http: settings shared by all web sites.
- server: one virtual host, which is one site or group of names.
- location: rules for a subset of URLs inside a server.
Debian packages include /etc/nginx/sites-enabled/* from the http context. The convention is to write each site in /etc/nginx/sites-available/ and enable it with a symlink:
sudo ln -s /etc/nginx/sites-available/example /etc/nginx/sites-enabled/example
sudo nginx -t
sudo systemctl reload nginxnginx -t checks syntax without touching the running server. A reload starts new workers with the new configuration and lets the old ones finish their requests. Always run nginx -t first, because a reload with a broken file is refused but a restart can leave you with no server.
Server blocks: choosing a virtual host
One Nginx instance can serve many sites. Each server block declares what it listens on and which names it answers to:
server {
listen 80;
server_name example.com www.example.com;
}Nginx picks a server for each request in two steps.
- It matches the address and port the connection arrived on against every
listendirective. Only the blocks listening there remain. - Among those, it compares the request's
Hostheader with eachserver_name, in this order: exact name, longest wildcard starting with*(such as*.example.com), longest wildcard ending with*, then the first matching regular expression in file order.
If nothing matches, the request goes to the default server for that address and port. That is the block marked listen 80 default_server;, or the first block in the configuration if none is marked. Do not leave this to chance. A request for an unknown name, or a bare IP address, would otherwise be served by whichever site was loaded first. Define an explicit catch-all:
server {
listen 80 default_server;
server_name _;
return 444;
}The name _ has no special meaning. It is a placeholder that no real host will match. Status 444 is Nginx-specific and closes the connection without a response.
root, index, and how URLs become file paths
The root directive sets a base directory. Nginx appends the full request URI to it:
| Directive | Request | File Nginx looks for |
|---|---|---|
| `root /var/www/example/public;` | `/css/site.css` | `/var/www/example/public/css/site.css` |
| `root /var/www/example/public;` | `/` | `index` files in `/var/www/example/public/` |
When the URI ends in /, Nginx tries each file named by index, in order. Set root once at the server level so every location inherits it. Repeating it in each location invites mismatches.
The related directive alias replaces the matched location prefix instead of appending to it:
location /static/ {
alias /srv/myapp/static/;
}A request for /static/app.css reads /srv/myapp/static/app.css. The same result with root would require root /srv/myapp;, which also needs the directory to be named static. Use alias when the URL path and the directory name differ. When you use it, end both the location and the alias path with a slash, or both without. A mismatch produces paths like /srv/myapp/staticapp.css.
Location matching
Inside a server, location blocks match the URI path (without the query string). There are four kinds of match:
| Syntax | Meaning |
|---|---|
| `location = /path` | Exact match only |
| `location ^~ /prefix/` | Prefix match that, if it is the longest prefix, skips regular expressions |
| `location ~ regex` / `location ~* regex` | Case-sensitive / case-insensitive regular expression |
| `location /prefix/` | Plain prefix match |
The order in which you write them does not decide the winner, except among regular expressions. Nginx uses this algorithm:
- If an
=location matches exactly, use it and stop. - Otherwise find the longest matching prefix location, including
^~ones. If that longest prefix has^~, use it and stop. - Otherwise test the regular expressions in file order. The first match wins.
- If no regular expression matches, use the longest prefix from step 2.
The usual surprise comes from step 3. A regular expression beats a plain prefix, even a longer and more specific one. If location /uploads/ and location ~ \.php$ both exist, a request for /uploads/shell.php goes to the regex block. Use ^~ when a directory must never be handled by a regex rule.
A complete example
This server block combines the pieces. Save it as /etc/nginx/sites-available/example:
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example/public;
index index.html index.php;
location / {
try_files $uri $uri/ =404;
}
location = /healthz {
access_log off;
default_type text/plain;
return 200 "ok\n";
}
location ^~ /assets/ {
expires 7d;
}
location ~* \.(?:css|js|png|jpg|svg)$ {
expires 1d;
}
location ~ /\.(?!well-known) {
deny all;
}
}Trace a few requests:
/healthzmatches the exact location and returnsokwithout reading any file./assets/logo.pngmatches both^~ /assets/and the image regex. Because the longest prefix has^~, Nginx never tests the regex, so the 7-dayexpiresapplies./img/logo.pngmatches no^~prefix, so the regex runs and sets a one-day cache lifetime./.envmatches the hidden-file regex and gets 403. The negative lookahead(?!well-known)keeps/.well-known/reachable, which certificate validation needs./aboutfalls tolocation /, wheretry_fileschecks/var/www/example/public/about, then that path as a directory, then returns 404.
try_files tests the listed paths in order and serves the first one that exists. The last argument is the fallback, either a status code like =404 or a URI for an internal redirect. A later chapter uses the redirect form to send application routes to index.php.
Testing without DNS
You do not need a real domain to test name-based selection. Send the Host header yourself:
curl -i -H "Host: example.com" http://127.0.0.1/healthz
curl -i -H "Host: unknown.test" http://127.0.0.1/healthz
curl -i -H "Host: example.com" http://127.0.0.1/.envThe first should return 200. The second should return an empty reply, because the catch-all closes the connection. The third should return 403.
Common mistakes
- Forgetting
nginx -t. A syntax error blocks the reload, and the old configuration stays active. - Wrong 404 versus 403. A 404 usually means the computed path does not exist, so print it mentally from
rootplus URI. A 403 usually means the file exists but thenginxworker user (www-dataon Debian) cannot read it or cannot traverse a parent directory, or a directory has no index file and autoindex is off. - A
locationnested in the wrong place. Locations belong inserver, or inside anotherlocation, never directly inhttp. - Two servers both claiming
default_serveron the same port. Nginx reports a duplicate default server when you test. - The same
server_namein two blocks. Nginx warns about a conflicting name and uses the first. - Assuming file order matters for prefixes. It matters only among regular expressions.
Exercise
A server has location /files/ { ... }, location ~ \.pdf$ { ... } and location ^~ /files/private/ { ... }. Which block handles /files/private/report.pdf, and which handles /files/report.pdf?
Show answer
/files/private/report.pdf goes to the ^~ /files/private/ block. It is the longest matching prefix and has ^~, so the regex is skipped. /files/report.pdf matches the prefix /files/ and the regex \.pdf$. The prefix has no ^~, so the regex is tested and wins.
Exercise
With root /var/www/site; at server level, what file does location /static/ { alias /srv/assets; } read for /static/app.css, and what fix is needed?
Show answer
It reads /srv/assetsapp.css, because the matched prefix /static/ is replaced by /srv/assets with no slash between them. Fix it by writing alias /srv/assets/;, so the path becomes /srv/assets/app.css.