nginx
How an nginx config is structured, how server and location are chosen, root vs alias, proxy_pass, testing and reloading
nginx is a web server and reverse proxy. The config is made of nested context blocks; for each request nginx picks one server and, inside it, one location, and their directives decide what to answer: serve a file, return a code or pass the request on.
Syntax
nginx [options]
Command-line options
| Option | What it does |
|---|---|
| (no options) | start; the master process goes to the background |
-t | test the config and exit: syntax, paths, certificates |
-T | same, and print the whole assembled config with all includes |
-s reload | re-read the config without stopping: new workers start, old ones finish their requests |
-s quit | graceful stop — wait for current requests |
-s stop | stop immediately |
-s reopen | reopen log files (after rotation) |
-c file | use another main config |
-g 'directives;' | add top-level directives, e.g. -g 'daemon off;' — don't go to the background |
-v / -V | version / version, build parameters and modules |
-q | with -t, show only errors |
If nginx runs as a service, systemctl reload nginx and systemctl restart nginx do the same.
Config structure
The main file is /etc/nginx/nginx.conf. On Debian and Ubuntu it includes conf.d/*.conf and sites-enabled/*; sites are placed in sites-available/ and enabled with a symlink in sites-enabled/.
user www-data; # main context: processes, logs
worker_processes auto;
events { worker_connections 768; }
http { # everything about HTTP
include mime.types;
access_log /var/log/nginx/access.log;
upstream backend { # server group for proxy_pass
server 127.0.0.1:9000;
}
server { # one site
listen 8080;
server_name example.local www.example.local;
root /srv/site;
index index.html;
location / { # rules for part of the URL space
try_files $uri $uri/ =404;
}
location /api/ {
proxy_pass http://backend/;
}
}
}
Every directive ends with ;. Directives of an outer block (root, index, access_log) are inherited by nested blocks unless they override them.
How server is chosen
- By
listen— the address and port the connection came to. - Among those — by the
Hostheader andserver_name, in this order: exact name → longest wildcard name starting with an asterisk (*.example.com) → ending with an asterisk (www.example.*) → first matching regex (~^…$). - Nothing matched — the
serverwithlisten … default_server, or without it the first one defined for this port.
server_name _; is just a name that matches nothing; what makes such a server a "catch-all" is default_server.
How location is chosen
| Kind | How it works |
|---|---|
location = /path | exact match — wins immediately |
location ^~ /path/ | prefix; if it is the longest prefix, regexes are not checked |
location ~ regex / ~* regex | case-sensitive / case-insensitive regex; the first match in file order |
location /path/ | plain prefix; the longest one is remembered, but regexes override it |
Order: exact match → longest prefix → if it has no ^~, regexes are checked top to bottom → if none matched, the longest prefix stays.
Common directives
| Directive | What it does |
|---|---|
listen 80; / listen 443 ssl; | port (and address: listen 127.0.0.1:8080;); default_server — the default server for the port |
server_name a.com *.a.com; | site names |
root /path; | directory with files: file path = root + URI |
alias /path/; | replaces the location prefix with a path (only inside location) |
index index.html; | which file to serve for a directory request |
try_files $uri $uri/ /index.html; | check files in order, the last option is the fallback (a URI or =404) |
return 301 https://$host$request_uri; | answer with a code right away; for 3xx — the redirect address, for 2xx/4xx — text |
rewrite ^/old/(.*)$ /new/$1 permanent; | rewrite the URI with a regex; permanent — 301, redirect — 302, last — search for a location again |
proxy_pass http://127.0.0.1:9000; | pass the request to another server or upstream |
proxy_set_header Host $host; | header sent to the backend |
add_header X-Name value; | add a header to the response |
allow 10.0.0.0/8; / deny all; | access by IP; checked in order |
auth_basic "text"; + auth_basic_user_file file; | password protection (htpasswd-format file) |
error_page 404 /404.html; | custom error page |
autoindex on; | show directory listings |
client_max_body_size 10m; | maximum request body size; larger — 413 |
access_log / error_log | where to write logs; access_log off; — don't write |
ssl_certificate / ssl_certificate_key | certificate and key for listen … ssl |
include file; | include another file (a * wildcard is allowed) |
Variables
| Variable | Value |
|---|---|
$uri | path without parameters, after normalization and rewrite |
$request_uri | original path including ?parameters |
$args / $arg_name | query string / a single parameter |
$host | host name from the request |
$remote_addr | client IP |
$scheme | http or https |
$http_name | any request header: $http_user_agent |
root vs alias, proxy_pass with a slash
| Config | Request | Where it goes |
|---|---|---|
location /static/ { root /srv/site; } | /static/a.css | file /srv/site/static/a.css — root + the whole URI |
location /files/ { alias /srv/files/; } | /files/a.txt | file /srv/files/a.txt — the prefix is replaced |
location /api/ { proxy_pass http://backend/; } | /api/users | the backend gets /users — the prefix is replaced with / |
location /api/ { proxy_pass http://backend; } | /api/users | the backend gets /api/users — URI unchanged |
Logs
By default /var/log/nginx/access.log and /var/log/nginx/error.log. An access log line (combined format):
127.0.0.1 - admin [13/Oct/2026:15:24:29 +0000] "GET /pub/ HTTP/1.1" 200 412 "-" "curl/8.5.0"
Client IP, Basic auth user, time, request line, response code, body size, Referer, User-Agent. error.log shows which file nginx tried to open and why it failed.
Examples
# test syntax before reloading — always
nginx -t && nginx -s reload
# which listen and server_name actually made it into the config
nginx -T 2>/dev/null | grep -E '^\s*(listen|server_name)'
# enable a site and apply
ln -s /etc/nginx/sites-available/mysite /etc/nginx/sites-enabled/
nginx -t && nginx -s reload
# run in the foreground — startup errors are visible
nginx -g 'daemon off;'
# is nginx listening on the right port
ss -tlnp | grep nginx
# test a virtual host by setting the Host header
curl -s -H 'Host: example.local' http://localhost:8080/
# password file for auth_basic
printf 'admin:%s\n' "$(openssl passwd -apr1 'secret')" > /etc/nginx/.htpasswd
# watch requests and errors
tail -f /var/log/nginx/access.log /var/log/nginx/error.log
# most frequent response codes
awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c | sort -rn
Pitfalls
nginx -tfirst.nginx -s reloadwith a broken config doesn't apply it: the old processes keep running with the old config, and the error is easy to miss. The test shows the file and line of the error.nginx -s reloadworks only if nginx is running: otherwise you get an error about/run/nginx.pid. Runningnginxagain while it is running givesbind() … Address already in use.- A regex beats a plain prefix.
location /images/loses tolocation ~ \.png$for/images/a.png. Need the prefix to win — write^~. - Slashes in
alias.location /files/withalias /srv/files;(no trailing slash) turns/files/a.txtinto/srv/filesa.txt. Put a trailing slash in bothlocationandalias— or in neither. rootinsidelocationdoesn't strip the path.location /static/ { root /srv/site/static; }will look for/srv/site/static/static/…. That's a case foralias.- A slash in
proxy_passchanges the URI the backend sees (see the table above). The backend answers 404 to a seemingly correct path — check that slash. add_headerin alocationcancels alladd_headers from the level above rather than adding to them. Headers set inserverdisappear in such alocation.error.logexplains 404 and 403: it shows exactly which path on disk nginx tried to open and why it failed (No such file or directory,Permission denied). For403, check the permissions on directories along the whole path — thewww-datauser needsxon each one.- A missing
;is the most common syntax error. The error message points to the line after the missing semicolon. location = /exactdoesn't match/exact/— for an exact match every character counts.