Sub topic 2
Matching host names with server_name
This chapter assumes you can edit files with sudo, that Nginx is installed from distribution packages and runs under systemd, and that you know what the HTTP Host header is. Each server block carries a server_name directive that lists the host names it answers for.
Matching host names with server_name
A browser that requests http://example.com/ sends example.com in the Host header. Nginx compares that value with the server_name list of each server block listening on the matching address and port.
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com/html;
index index.html;
}Enabling a site: validate with nginx -t, then reload
On Debian and Ubuntu, a file in /etc/nginx/sites-available/ is active only when a symlink to it exists in /etc/nginx/sites-enabled/. Create the link, then test the full configuration before reloading.
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginxHow Nginx picks the server block for a request
Nginx first filters server blocks by listen address and port. It then compares the Host header with each server_name, checking exact names, then wildcards, then regular expressions. If nothing matches, the default server for that socket answers.
Testing each site before DNS points at it
You can test a site before its DNS record exists. Send the Host header yourself to the server's address:
curl -H 'Host: example.com' http://127.0.0.1/
curl --resolve example.com:80:127.0.0.1 http://example.com/The first command sends the header directly. The second makes curl resolve the name to 127.0.0.1 for one request, so the request follows the same path a real visitor's would. If the response shows the wrong site, check the server_name lists of your blocks.
Exercise
A request arrives on port 80 with the Host header shop.example.com, and no server block lists that name. Which server block answers?
Show answer
The server block marked default_server for that address and port. If none is marked, Nginx uses the first server block defined for it.