← Full reference

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

OptionWhat it does
(no options)start; the master process goes to the background
-ttest the config and exit: syntax, paths, certificates
-Tsame, and print the whole assembled config with all includes
-s reloadre-read the config without stopping: new workers start, old ones finish their requests
-s quitgraceful stop — wait for current requests
-s stopstop immediately
-s reopenreopen log files (after rotation)
-c fileuse another main config
-g 'directives;'add top-level directives, e.g. -g 'daemon off;' — don't go to the background
-v / -Vversion / version, build parameters and modules
-qwith -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

  1. By listen — the address and port the connection came to.
  2. Among those — by the Host header and server_name, in this order: exact name → longest wildcard name starting with an asterisk (*.example.com) → ending with an asterisk (www.example.*) → first matching regex (~^…$).
  3. Nothing matched — the server with listen … 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

KindHow it works
location = /pathexact match — wins immediately
location ^~ /path/prefix; if it is the longest prefix, regexes are not checked
location ~ regex / ~* regexcase-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

DirectiveWhat 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_logwhere to write logs; access_log off; — don't write
ssl_certificate / ssl_certificate_keycertificate and key for listen … ssl
include file;include another file (a * wildcard is allowed)

Variables

VariableValue
$uripath without parameters, after normalization and rewrite
$request_urioriginal path including ?parameters
$args / $arg_namequery string / a single parameter
$hosthost name from the request
$remote_addrclient IP
$schemehttp or https
$http_nameany request header: $http_user_agent

root vs alias, proxy_pass with a slash

ConfigRequestWhere it goes
location /static/ { root /srv/site; }/static/a.cssfile /srv/site/static/a.css — root + the whole URI
location /files/ { alias /srv/files/; }/files/a.txtfile /srv/files/a.txt — the prefix is replaced
location /api/ { proxy_pass http://backend/; }/api/usersthe backend gets /users — the prefix is replaced with /
location /api/ { proxy_pass http://backend; }/api/usersthe 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 -t first. nginx -s reload with 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 reload works only if nginx is running: otherwise you get an error about /run/nginx.pid. Running nginx again while it is running gives bind() … Address already in use.
  • A regex beats a plain prefix. location /images/ loses to location ~ \.png$ for /images/a.png. Need the prefix to win — write ^~.
  • Slashes in alias. location /files/ with alias /srv/files; (no trailing slash) turns /files/a.txt into /srv/filesa.txt. Put a trailing slash in both location and alias — or in neither.
  • root inside location doesn't strip the path. location /static/ { root /srv/site/static; } will look for /srv/site/static/static/…. That's a case for alias.
  • A slash in proxy_pass changes the URI the backend sees (see the table above). The backend answers 404 to a seemingly correct path — check that slash.
  • add_header in a location cancels all add_headers from the level above rather than adding to them. Headers set in server disappear in such a location.
  • error.log explains 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). For 403, check the permissions on directories along the whole path — the www-data user needs x on each one.
  • A missing ; is the most common syntax error. The error message points to the line after the missing semicolon.
  • location = /exact doesn't match /exact/ — for an exact match every character counts.

See also

curl · ss · openssl · service · logrotate · chmod