Sub topic 1
How Nginx configuration is organized, tested and reloaded
Prerequisites
This chapter assumes you can use the Linux command line and edit files with sudo. You should understand HTTP requests, responses and status codes, and have Nginx installed from your distribution's package manager. You should also know that a TCP port is a numbered endpoint on a host, such as port 80 for web traffic.
Configuration structure
Nginx reads its settings from /etc/nginx/nginx.conf. The file is made of nested blocks called contexts. The http block holds web settings, each server block describes one virtual site, and each location block inside a server handles a set of request paths.
Testing and reloading
Nginx can check its configuration before it uses it. Run the test, then reload only if the test passes:
sudo nginx -t && sudo systemctl reload nginxA reload applies the new configuration and keeps existing connections open. A restart stops them, so prefer reload on live servers.
> Replace this line with a callout.
What a reverse proxy does
A forward proxy sends a client's requests out to the internet. A reverse proxy works the other way. It receives requests from clients and passes them to an application server behind it. The client talks only to Nginx.
This first site forwards all requests to an application on local port 3000:
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
}
}Choosing a server and matching locations
Nginx first picks a server block by matching the listening address and port, then the server_name. Inside that server, it picks one location by comparing the request path.
| Modifier | Match type | Example |
|---|---|---|
| `=` | Exact match, stops search | `location = /health` |
| `^~` | Longest prefix, skips regex | `location ^~ /static/` |
| `~` | Case-sensitive regex | `location ~ \.php$` |
| (none) | Longest prefix | `location /api/` |
Checking which location wins
Nginx picks the longest matching prefix unless a regex or exact match takes priority, so more specific paths should be written with more specific prefixes.
How proxy_pass rewrites the request URI
The proxy_pass directive changes the path depending on whether it ends with a slash.
location /api/ {
proxy_pass http://127.0.0.1:3000/;
}With the trailing slash, a request for /api/users reaches the backend as /users. Without a URI part, as in proxy_pass http://127.0.0.1:3000;, the backend receives the full path /api/users.
Exercise
Exercise
With location /app/ { proxy_pass http://127.0.0.1:3000/; }, which path does the backend receive for a request to /app/login?
Show answer
/login. The matched prefix /app/ is replaced by the URI / in proxy_pass.