Linux Labs

Web stack / Stage 1 of 9

How nginx picks a site and a file

Not running Starting usually ~20 s
Leave the lesson

Step 2 of 7 · theory · 6 min

The site name travels in the request

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 >:

text
> GET / HTTP/1.1
> Host: docs.lab.test

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:

nginx
server {
    listen 80 default_server;
    server_name portal.lab.test;
    root /srv/www/portal;
    index index.html;
}

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.

Check yourself 1 question

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 the Host header.

  • 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 Host header; the address and port only bring the request to nginx.
  • A site is a server block: nginx picks it by server_name among the blocks for the same port.
  • A name that is in no server_name goes to the default server, the block with default_server.
Ubuntu 24.04
Loading…