One nginx takes requests for both sites on port 80. This step shows how it knows which site is being asked for.
curl handles a site address in two stages. It turns the name docs.lab.test into the address 127.0.0.1 and connects to port 80 — the connection needs nothing more from the name. Then it sends an HTTP request and writes the site name into it as the Host header. curl -v shows the request in lines starting with >:
In the nginx configuration a site is a server block. In it, listen is the port the block takes requests on, server_name lists the site's names, and root is the directory with its files. This is the portal:
A request arrives on port 80, and nginx looks among the blocks for that port for one whose server_name contains the name from Host. If none does, the default server answers: the block with the default_server parameter in listen, or, without that parameter, the first block for the port.
You can set the header by hand: curl -H 'Host: docs.lab.test' http://127.0.0.1/ connects to 127.0.0.1 and asks for the site named in -H. That is how you test a site whose name does not lead anywhere yet.
The docs block is still not enabled. What will curl -H 'Host: nosuch.lab.test' http://127.0.0.1/ print?
-
nginx does not read the docs block, and nosuch.lab.test matches no
server_name: the default server, the portal, answers. -
curl connects to the address in the URL, 127.0.0.1, and does not look up the name from
-H: it puts it into theHostheader. -
nginx does not reject an unknown name: the default server, the portal, gets the request and serves its page.
The name nosuch.lab.test matches no server_name, so the portal's block with default_server gets the request. curl connects to 127.0.0.1 from the URL and only passes the name from -H in the header.
Key points
-
The site name reaches nginx in the
Hostheader; the address and port only bring the request to nginx. -
A site is a
serverblock: nginx picks it byserver_nameamong the blocks for the same port. -
A name that is in no
server_namegoes to the default server, the block withdefault_server.