Sub topic 6
Server blocks and virtual hosts
This chapter assumes you have Nginx installed and running under systemd, and that you can edit files with sudo. You should also know how nginx -t and systemctl reload nginx work, and that an HTTP/1.1 request carries a Host header. The goal is to host several sites on one server and to predict which server block answers a given request.
What a server block is
A virtual host is one site served by a machine that hosts many. Nginx implements virtual hosts with server blocks. Each server block lives in the http context and describes one site: the addresses and ports it listens on, the names it answers to, and how it handles requests.
Nginx picks a server block in two stages:
- It compares the IP address and port of the connection with each block's
listendirectives. - Among the blocks that match, it compares the request's
Hostheader with each block'sserver_namevalues.
If nothing matches in the second stage, Nginx uses the default server for that address and port.
A basic static site
This is the block from the plan for serving static files on two names:
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}listen 80;accepts connections on port 80 on all IPv4 addresses. Addlisten [::]:80;to accept IPv6 as well.server_namelists every host name this block answers to.rootis the directory that Nginx maps URIs onto. A request for/about.htmlreads/var/www/example.com/html/about.html.try_fileschecks for a file, then a directory, and returns 404 if neither exists. Location matching is covered in the next chapter.
Where to put the file
The main file /etc/nginx/nginx.conf includes other files, so each site can have its own file. The layout depends on the distribution.
| Distribution family | Site files live in | How a site is enabled |
|---|---|---|
| Debian, Ubuntu | `/etc/nginx/sites-available/` | Symlink into `/etc/nginx/sites-enabled/` |
| RHEL, Fedora, Rocky | `/etc/nginx/conf.d/` | File name must end in `.conf` |
Check which include lines your nginx.conf contains, because a file that no include pulls in is silently ignored.
On Debian or Ubuntu, create the site like this:
sudo mkdir -p /var/www/example.com/html
echo '<h1>example.com works</h1>' | sudo tee /var/www/example.com/html/index.html
sudo nano /etc/nginx/sites-available/example.com
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/example.com
sudo nginx -t && sudo systemctl reload nginxPut the server block shown above in the file you open with nano. To disable the site later, remove the symlink and reload. The file in sites-available stays as a record.
Testing without changing DNS
You do not need a real DNS record to test a virtual host. Send the Host header yourself:
curl -i -H "Host: example.com" http://127.0.0.1/
curl -i --resolve www.example.com:80:127.0.0.1 http://www.example.com/The first command sets the header directly. The second makes curl resolve the name to 127.0.0.1 for that one request, which is closer to what a real client does. Both are more reliable than editing /etc/hosts, because they leave no state to clean up.
How server_name is matched
server_name accepts exact names, wildcards, and regular expressions. When several blocks listen on the same socket, Nginx tests the Host value in this fixed order and stops at the first category that matches:
| Priority | Type | Example |
|---|---|---|
| 1 | Exact name | `www.example.com` |
| 2 | Longest wildcard starting with `*` | `*.example.com` |
| 3 | Longest wildcard ending with `*` | `mail.*` |
| 4 | First matching regular expression, in file order | `~^(?<sub>.+)\.example\.com$` |
| 5 | The default server | `listen 80 default_server;` |
The order of blocks in the file matters only for regular expressions. Exact names and wildcards are chosen by specificity, not position.
A leading-dot name is a shortcut. .example.com matches example.com and every subdomain, so it replaces listing example.com and *.example.com separately.
A regular expression name starts with ~. Named captures become variables you can use in the block:
server {
listen 80;
server_name ~^(?<tenant>[a-z0-9-]+)\.apps\.example\.com$;
root /var/www/tenants/$tenant;
}A request for acme.apps.example.com serves files from /var/www/tenants/acme. Be careful here. The captured value comes from the client, so keep the character class narrow, as it is above, to rule out .. and slashes in the path.
The default server
If no server_name matches, Nginx does not return an error. It uses the default server for that listen socket. Unless you mark one explicitly, the default is the first block that defines that socket in the loaded configuration. That choice depends on include order, so it is fragile.
State your default explicitly. A common pattern is a catch-all that refuses unknown hosts:
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
return 444;
}Status 444 is an Nginx-specific code that closes the connection without sending a response. The name _ has no special meaning. It is simply a name that no real host will use, and the default_server parameter does the actual work.
This block protects you in two ways. Scanners that request your server by IP address do not see one of your real sites. And a DNS record that someone points at your IP does not cause your site to be served under a foreign name.
> The default_server flag belongs to the listen socket, not to the block. You may have one default per address and port pair, so a block with listen 80 default_server and another with listen 443 ssl default_server do not conflict.
Several sites on one server
Two sites with separate roots look like this:
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com/html;
index index.html;
}
server {
listen 80;
server_name blog.example.org;
root /var/www/blog.example.org/html;
index index.html;
}Because both blocks listen on the same socket, the Host header alone decides which one answers. Set root inside each server block, or set it once at http level for a shared default and override it where needed. Directives are inherited downward from http into server, so a value set higher up applies to every block below it unless that block sets its own.
You can also split sites by address. If the machine has two IP addresses, listen 192.0.2.10:80; and listen 192.0.2.11:80; separate the sites at stage one, before server_name is consulted. This is rarely needed now that name-based hosting is standard.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| The wrong site appears for a name | No `server_name` matched, so the default server answered | Check spelling and test with `curl -H "Host: ..."` |
| `conflicting server name "x" on 0.0.0.0:80, ignored` | The same name appears in two blocks on one socket | Remove the duplicate. Nginx ignores the later one |
| `duplicate default server` | Two blocks declare `default_server` for one socket | Keep one |
| 403 Forbidden | The `nginx` worker user cannot traverse a parent directory or read files, or there is no index file | Check `namei -l /var/www/example.com/html/index.html` and the `user` directive in `nginx.conf` |
| 404 for every path | `root` points to the wrong directory | Remember that `root` is joined with the URI, so `/var/www/site/html` plus `/a` is `/var/www/site/html/a` |
| The site file has no effect | The symlink is missing or the `include` does not cover the file | Run `sudo nginx -T` to dump the full loaded configuration and search it |
nginx -T (capital T) tests the configuration and prints every loaded file. It is the quickest way to see whether your block is actually part of the running configuration.
Check your understanding
Exercise
A server has three blocks on listen 80. Block A has server_name *.example.com;, block B has server_name www.example.com;, and block C has server_name ~^www\..+$;. Which block handles a request with Host: www.example.com, and why? Which block handles Host: shop.example.com?
Show answer
Block B handles www.example.com, because an exact name has the highest priority and wins over wildcards and regular expressions regardless of file order. Block A handles shop.example.com, because no exact name matches and the wildcard *.example.com is checked before regular expressions. Block C would only be used if neither an exact name nor a wildcard matched, for example www.example.net.
Exercise
You add a new site file on Ubuntu and run sudo nginx -t && sudo systemctl reload nginx. The test passes, but curl -H "Host: new.example.com" http://127.0.0.1/ returns the content of a different site. Give two likely causes and a command that helps you find out which one applies.
Show answer
Likely causes are that the file is not enabled (no symlink in sites-enabled, or a conf.d file not ending in .conf), so Nginx never loaded the block and the default server answered. Another is a typo in server_name, so the name does not match. Running sudo nginx -T | grep -n new.example.com shows whether the name appears anywhere in the loaded configuration. No output means the file was not loaded. Output in the wrong place means a spelling or placement problem.