Sub topic 2
Server blocks: one Nginx, many sites
This chapter assumes you are comfortable with the Linux command line and a text editor, and that you know how DNS maps names to IP addresses. It also assumes you know what an HTTP request and its Host header are, and that Nginx is installed from distribution packages and running under systemd. You should be able to use sudo and manage file ownership. The chapter introduces the server block itself. Later chapters cover how Nginx chooses between blocks, default servers, logs, redirects, proxying and HTTPS in detail.
What a server block is
A server block is a server { ... } section in the Nginx configuration. It describes one virtual server: the addresses and ports it accepts connections on, the host names it answers to, and what it does with the requests it receives. Other web servers call this a virtual host.
Without server blocks, one Nginx instance would serve one site. With them, a single Nginx process on a single IP address can serve example.com, example.org and app.example.net, each with its own files, logs and behavior.
Server blocks live inside the http { ... } context. The usual structure looks like this:
http {
server {
# site one
}
server {
# site two
}
}On Debian and Ubuntu, the packaged nginx.conf does not contain the blocks directly. It pulls them in with include /etc/nginx/sites-enabled/*; inside http. You write each site in its own file, and the file's contents are placed into the http context at that point.
A minimal server block
This block serves static files for two host names from its own directory.
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
root /var/www/example.com/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}Each directive has a job:
| Directive | Meaning |
|---|---|
| `listen 80;` | Accept IPv4 connections on port 80 on all addresses. |
| `listen [::]:80;` | Accept IPv6 connections on port 80. |
| `server_name` | The host names this block is meant to answer for. |
| `root` | The directory that URLs are mapped onto. |
| `index` | The file served when the URL ends in a directory. |
| `location /` | Rules for all URIs that start with `/`. |
| `try_files` | Try the URI as a file, then as a directory, then return 404. |
With this block, a request for /about.html is served from /var/www/example.com/html/about.html. A request for / is served from /var/www/example.com/html/index.html. A request for a path that does not exist returns 404 because of =404.
root is appended to the URI, not substituted for a prefix. This differs from alias, which you will meet when you need to map a location onto an unrelated directory.
One block per site
To host a second site, add a second block with a different server_name and a different root. Nginx reads the Host header of each request and sends it to the matching block.
server {
listen 80;
listen [::]:80;
server_name example.org www.example.org;
root /var/www/example.org/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}Both blocks listen on the same address and port. That is allowed, and it is the whole point. The listen directive decides which blocks are candidates for a connection. The server_name directive picks among the candidates using the Host header.
The diagram shows the flow for one request.
Publishing the two sites
The commands below create a document root and a test page for each site, enable both site files by symlink, and reload Nginx only if the configuration test passes. This is the sites-available and sites-enabled layout used by the Debian and Ubuntu packages. The server block files themselves are assumed to exist already as /etc/nginx/sites-available/example.com and /etc/nginx/sites-available/example.org.
sudo mkdir -p /var/www/example.com/html /var/www/example.org/html
echo '<h1>example.com</h1>' | sudo tee /var/www/example.com/html/index.html
echo '<h1>example.org</h1>' | sudo tee /var/www/example.org/html/index.html
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo ln -s /etc/nginx/sites-available/example.org /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginxThe && matters. nginx -t parses the whole configuration and exits with a non-zero status if anything is wrong, so a broken file never reaches reload. A reload also keeps serving existing connections with the old configuration until the new one is accepted. If the new configuration fails to load, the old workers continue, so a typo does not take the server down.
Distributions that do not use sites-enabled, such as many RPM-based ones, put site files in /etc/nginx/conf.d/ with a .conf suffix. The server block syntax is the same. Only the include path differs.
Checking which block answers
Before DNS points at the server, you can test each block by sending the Host header yourself. Both commands below talk to the local machine.
curl -H 'Host: example.org' http://127.0.0.1/
curl --resolve example.com:80:127.0.0.1 http://example.com/The first command connects to 127.0.0.1 and sets the Host header by hand. The second makes curl resolve example.com to 127.0.0.1 for that one request, so the URL and the header both say example.com. This second form also works for HTTPS, because curl sends the right name for TLS as well.
With the test pages above, the first command should print <h1>example.org</h1> and the second <h1>example.com</h1>. If both print the same page, the request is not reaching the block you expect.
Details that matter in practice
Server blocks are matched, not ordered by file
Nginx does not choose a block by file name or by reading top to bottom for the best fit on server_name. It first narrows by listen and then compares the Host header with every server_name among the candidates. Exact names win over wildcards, and wildcards win over regular expressions. File order affects only which block becomes the implicit default, because sites-enabled/* is expanded alphabetically.
Each block is self-contained
Directives such as root, index and access_log set in one server block do not apply to another. If you set root at the http level, every server block inherits it unless it sets its own. For separate sites, set root in each block so that no site accidentally serves another site's files.
Document root permissions
The Nginx worker user, usually www-data on Debian and Ubuntu or nginx on RPM-based systems, must be able to enter every directory in the path and read the files. A missing execute bit on a parent directory is a common cause of 403 responses. Files in /var/www you create with sudo are owned by root, which is fine as long as they are world-readable (644 for files, 755 for directories).
Binding conflicts
Two server blocks can both say listen 80; and that is normal. What fails is listening on an address and port that another program holds. In that case nginx -t passes the syntax check but the reload fails with bind() ... failed (98: Address already in use). Check with sudo ss -ltnp 'sport = :80'.
Duplicates
If two blocks use the same server_name on the same address and port, Nginx accepts the configuration with a warning (conflicting server name ... ignored). It uses the first block and ignores the second. Read the output of nginx -t, not just the exit status.
Common mistakes
| Symptom | Likely cause |
|---|---|
| Every site shows the first site's content | `server_name` is misspelled, so requests fall back to the default block. |
| `nginx -t` reports `unknown directive` | A typo or a missing semicolon in a directive. |
| 403 Forbidden | No `index` file in the directory and autoindex is off, or the worker user cannot read the path. |
| 404 Not Found | The `root` path or file name does not match the URL. |
| The new site does not appear | The symlink in `sites-enabled` is missing, or Nginx was not reloaded. |
Summary of the working model
- A server block is a virtual server inside the
httpcontext. listenselects which blocks can receive a connection on a given address and port.server_nameselects the block for a request among those candidates, using theHostheader.rootandindexdefine where a block's files come from.nginx -tvalidates andsystemctl reload nginxapplies the change without dropping connections.
Exercise
You enabled a new site for example.org, ran the reload, and curl to the server with the Host header example.org still returns the page of example.com. Name two checks that would locate the cause.
Show answer
First, confirm the symlink exists in /etc/nginx/sites-enabled and run sudo nginx -T | grep server_name to see whether the example.org block is loaded and spelled correctly. Second, run sudo nginx -t and read its output for warnings such as "conflicting server name", which would mean another block claims the same name and the new one is ignored. Also verify that the reload actually succeeded with systemctl status nginx.
Exercise
Why does the command sudo nginx -t && sudo systemctl reload nginx use && instead of ;?
Show answer
With &&, the reload runs only if nginx -t exits with status 0. With ;, the reload would run even after a failed test. A reload with a broken configuration does not apply it, but the failure is harder to notice, and the habit is unsafe for other commands.