Nginx Basics — DevOps

Nginx is a web server (a program that answers HTTP requests) on ports 80 and 443. Nginx can also be a reverse proxy (forwarding requests to an app behind it)…

People using notes-api start reporting that the attachments they uploaded won't open, just 404 Not Found. You check on web-1, and the file is there in the upload folder, intact. The file isn't the problem. The way nginx picks a rule for that request is.

Nginx (pronounced "engine-x") is a web server: a program that waits for HTTP requests on port 80 (and 443 for HTTPS), then answers them. It answers either with a file from disk or by forwarding the request to an app behind it. Picture the information desk in a shopping mall. The mall has one address, but many shops. A visitor names the shop and the item they want, and the person at the desk shows them where it is. Here the mall is web-1 with its one IP, the person at the desk is nginx, and each shop is one site. The shop's name is the Host header (a note in the request that holds the domain name the browser opened). The item is the URL path, the part of the URL after the domain name, such as /logo.svg.

Installing nginx on web-1

On web-1 (Ubuntu 24.04), sudo apt install nginx installs it, and systemd starts it right away. curl -I http://localhost (headers only) gets the answer HTTP/1.1 200 OK with Server: nginx/1.24.0 (Ubuntu): that's the default "Welcome to nginx!" page.

Server block: one site, one block

notes-api's site at notes.example.com has static files (files sent as they are): the front page index.html and its assets (CSS, JavaScript, images) in /var/www/notes, plus the attachments people upload. The Express app itself is connected later, in the Reverse Proxy & Load Balancing lesson. For now nginx serves the static files. Its config is written in /etc/nginx/sites-available/notes:

server {
    listen 80;
    listen [::]:80;
    server_name notes.example.com www.notes.example.com;
    root /var/www/notes;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

Switch the site on with sudo ln -s /etc/nginx/sites-available/notes /etc/nginx/sites-enabled/. Switch the default page off with sudo rm /etc/nginx/sites-enabled/default: this removes only the symlink, and the real file in sites-available stays. Then test and apply the config (the last section of this lesson).

In the exercise, you build the text of a server block from an object { port, serverName, root, locations }. Lines inside server are indented 4 spaces, the inside of a location 8 spaces, and every directive ends with ;. For { port: 80, serverName: "myapp.com", root: "/var/www/html", locations: [{ path: "/", directive: "try_files $uri /index.html" }] } the result is exactly:

server {
    listen 80;
    server_name myapp.com;
    root /var/www/html;
    location / {
        try_files $uri /index.html;
    }
}

Nginx picks a server block from the port and Host

A browser opening http://notes.example.com connects to web-1's IP, 203.0.113.10, on port 80. (How the browser gets the IP from the domain name is in the next lesson, DNS Basics.) Then the browser sends Host: notes.example.com. Nginx takes every server block that listens on that port, and matches Host against their server_name. If none matches, nginx uses that port's default server: the server block marked default_server, or the first server block if none is marked.

Below the notes server block, web-1 has one block for requests that match no site:

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;
    return 444;
}
Request Host Server block Result
curl -I http://notes.example.com/ notes.example.com notes 200 OK
curl -I http://www.notes.example.com/ www.notes.example.com notes 200 OK
curl -I http://203.0.113.10/ 203.0.113.10 default connection dropped

server_name _ is just a name that can never match. return 444 is a special nginx code: nginx closes the connection without any answer, so curl writes curl: (52) Empty reply from server. Bots (automatic programs) scanning random IPs get nothing.

The order nginx picks a location in

Here are all the locations in the notes site's server block, the same as in the Lab:

    location = /favicon.ico { access_log off; log_not_found off; }

    location /attachments/ {
        alias /srv/notes-api/storage/attachments/;
    }

    location ~* \.(jpg|jpeg|png|svg|css|js)$ { expires 30d; }

    location / {
        try_files $uri $uri/ =404;
    }

Nginx picks a location in four steps. The order of prefix locations in the file makes no difference, but the order of regexes does:

  1. Is there an = that matches exactly? Use it, done.
  2. Find the longest prefix that matches. If that prefix is marked ^~, use it, done.
  3. Check the regexes in the order they're written in the file. The first regex that matches wins.
  4. No regex matched? Use the longest prefix from step 2.

Try the four steps yourself before you look at the table: where does GET /attachments/a4c2e9f1.jpg land?

Path Location picked Result
/favicon.ico = /favicon.ico (step 1) 200, the favicon
/ / (step 4) 200, index.html
/notes/12 / (step 4) 404, the API isn't connected yet
/assets/app.3f9a1c.js regex (step 3) 200, cached 30 days
/attachments/a4c2e9f1.jpg regex (step 3) 404 Not Found

Look at the last row. In step 2, the longest prefix is /attachments/, but /attachments/ is a plain prefix (without ^~). So nginx continues to step 3, and .jpg matches the regex. The regex wins. That regex location has no alias, so nginx looks for the file under root: /var/www/notes/attachments/a4c2e9f1.jpg. That file doesn't exist, so the answer is 404. That's why people report attachments that won't open. The fix is one mark: location ^~ /attachments/. Now step 2 stops at /attachments/, so the regex is never checked for attachment paths.

Check with nginx -t first, then reload

Every time the config changes, test it first, then apply it:

$ sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
$ sudo systemctl reload nginx

Now say the semicolon after root /var/www/notes (line 5) is missing. Nginx keeps reading until the next semicolon, so it sees root /var/www/notes index index.html;: one directive with three arguments, while root takes only one. nginx -t refuses it:

$ sudo nginx -t
nginx: [emerg] invalid number of arguments in "root" directive in /etc/nginx/sites-enabled/notes:6
nginx: configuration file /etc/nginx/nginx.conf test failed

⚠️ Small config mistakes that cause big trouble

TL;DR: Nginx is a web server (a program that answers HTTP requests) on ports 80 and 443. Nginx can also be a reverse proxy (forwarding requests to an app behind it), covered in the Reverse Proxy & Load Balancing lesson. Each site's config is written in sites-available and switched on through a symlink (a shortcut file) in sites-enabled. A server block (one site: server { listen; server_name; root; location }) is picked by port and Host header (the domain name the browser opened). A request whose Host matches no site falls to the default_server. A location (a rule for a URL path) is picked in this order: an exact =, then the longest prefix (start of the path), stopping there if it's ^~, then the ~/~* regexes (text patterns) in file order, then that longest prefix. Every directive (instruction) ends with ;. Always run sudo nginx -t (test the config) first, then sudo systemctl reload nginx (or nginx -s reload). A reload drops no connections and refuses a broken config.

⚡ One site, one server block

Write:

server {
    listen 80;
    server_name notes.example.com www.notes.example.com;
    root /var/www/notes;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

Meaning: One server block (server { }) is one site in nginx, the web server that answers requests. Nginx picks a server block by port (listen) and Host header (the domain name the browser opened), which is matched against server_name. root is the folder of the site's files. location / is the rule for every URL path (the part after the domain name). Inside it, try_files sends the file at the requested path ($uri) or the folder at that path (with its index file). If neither exists, the answer is 404. Every directive (instruction) ends with ;.

⚡ What doesn't match falls to the default

Write:

server {
    listen 80 default_server;
    server_name _;
    return 444;
}

Meaning: A request whose Host matches no server_name, for example a request straight to web-1's IP 203.0.113.10, falls to the default server: the server block marked default_server. server_name _ is a name that can never match. return 444 closes the connection without any answer.

⚡ A regex beats a plain prefix

Write:

location ^~ /attachments/ {
    alias /srv/notes-api/storage/attachments/;
}
Guess first: the same server block also has the regex (text pattern) location ~* \.(jpg|jpeg|png|svg|css|js)$ for paths that end in .jpg, .png and so on. Without ^~, where does GET /attachments/a4c2e9f1.jpg land?

In the regex ~* \.(jpg|...)$, because a plain prefix (the start of a path, without ^~) loses to a regex that matches. The regex location has no alias, so nginx looks for the file under root, in /var/www/notes/attachments/, doesn't find it, so 404.

Meaning: Nginx picks a location in this order: an exact =, then the longest prefix (stopping there if it's marked ^~), then the regexes in file order. ^~ means the regexes are never checked for paths in /attachments/, and alias reads the files from notes-api's upload folder.

⚡ Test first, then reload

Write:

sudo nginx -t && sudo systemctl reload nginx

Meaning: nginx -t checks the config without changing what's running. && runs the second command only when the first one succeeds. reload reads the new config without dropping connections, and refuses a broken config, so the old config keeps serving.

What you will learn