Sheet ⁨04⁩ · ⁨Cheatsheets⁩Surveyed ⁨2026⁩
Cheatsheets

Nginx

A practical Nginx reference. Server blocks and the location matching order, reverse proxying to an upstream, TLS termination, gzip and brotli, rate limiting, and the commands you reach for when a config will not load.

6 Categories8 Sections17 ExamplesPublished: 20 Nov 2026Updated: 21 Nov 2026
NginxReverse ProxyTLSLoad BalancingRate LimitingWeb ServerConfiguration

Most nginx confusion comes from one place: the order it uses to pick a location block. It is not the order in the file, and it is not the first thing that matches.

Prefix blocks are ranked by length, so moving one up the file changes nothing. File order matters only among regex blocks, at step 4. The red panel is the trap that follows: a broad regex quietly outranks the prefix block you wrote for your static files, and the fix is the two characters ^~.

Two consequences fall out of that order. A longer prefix always beats a shorter one regardless of position, so reordering the file is almost never the fix. And a regex that matches beats the prefix nginx had remembered, which is why a location ~* \.png$ further down the file will happily steal requests from the location /images/ above it.

On AWS the more useful question is which of nginx’s jobs something else has already done.

TLS terminates at the load balancer with a certificate from ACM, and health checks already exist. The red panel lists the four jobs that get done twice, including the X-Forwarded-For handling that decides whether your rate limiter sees real clients or sees the load balancer as one very busy visitor.

The reference below is grouped the way the work splits: the shape of a config file, choosing a server and a location, proxying to an application, TLS, the performance directives, and the handful of commands for when none of it is behaving.

Config structure

How a config file is organised, and which directives are legal where.

Contexts

The nesting that decides where a directive may appear.

The four contexts you write in

A directive is only legal in certain contexts, and the error message names the context rather than the fix, so knowing the nesting is most of debugging a config.

Code
# main context: worker processes, user, error_log
user www-data;
worker_processes auto;
events { worker_connections 1024; }
http {
# http context: gzip, log_format, upstream, mime types
include /etc/nginx/mime.types;
server {
# server context: listen, server_name, ssl_certificate
listen 80;
server_name example.com;
location / {
# location context: root, proxy_pass, try_files
root /var/www/html;
}
}
}
  • Most directives inherit downward: set `gzip on` in `http` and every server and location gets it unless one overrides it.
  • Inheritance is by replacement, not merge. A `location` with its own `add_header` discards every `add_header` from its parent, which surprises people writing security headers.

Where the files live

The `sites-available` and `sites-enabled` split is a Debian and Ubuntu convention, not an nginx feature. RHEL and the official image use `conf.d` only.

Code
Terminal window
/etc/nginx/nginx.conf # main file, includes the rest
/etc/nginx/conf.d/*.conf # usual place for your servers
/etc/nginx/sites-available/ # Debian convention: written here
/etc/nginx/sites-enabled/ # symlinked here to activate
  • Enable a site with `ln -s ../sites-available/x.conf .` from inside `sites-enabled`, and disable by removing the symlink.
  • A file in `conf.d` that does not end in `.conf` is silently ignored, which is a fine way to lose an hour.

Server blocks and name matching

Which server block answers a request, and what happens when none obviously does.

A minimal pair of server blocks

The first block catches anything that does not match a real host name. `return 444` closes the connection without a response, which is the usual answer to bots probing by IP address.

Code
server {
listen 80 default_server;
server_name _;
return 444; # close without responding
}
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example;
}
  • Without an explicit `default_server`, the first block for that port becomes the default, which is rarely the one you meant.
  • `server_name _;` is not special syntax. It is simply a name no real host can have, so it never matches by accident.

The matching order for server_name

Nginx tries these in order and stops at the first match, so an exact name always beats a wildcard no matter where each appears in the file.

Code
server_name example.com; # 1. exact
server_name *.example.com; # 2. leading wildcard
server_name mail.*; # 3. trailing wildcard
server_name ~^www\d+\.example\.com$; # 4. regex, in file order
  • If nothing matches, the `default_server` for that listen port answers.
  • A regex `server_name` can capture: `~^(?<sub>.+)\.example\.com$` makes `$sub` available in the block.

Location matching

The order nginx uses to choose a location block, which is the source of most surprises.

The matching order

Exact, then longest prefix, then regex, and only one of those steps cares about file order.

The five steps, in order

Nginx checks for an exact match, remembers the longest matching prefix, then tries regex blocks in file order. A matching regex beats the remembered prefix unless that prefix used `^~`.

Code
location = /healthz { return 200 'ok'; } # 1. exact, wins outright
location ^~ /assets/ { root /var/www; } # 3. prefix, stops the search
location /images/ { root /var/www; } # 2. prefix, remembered
location ~* \.(png|css)$ { proxy_pass http://app; } # 4. regex, file order
location / { proxy_pass http://app; } # 5. fallback
  • Prefix blocks are ranked by length, so their order in the file is irrelevant. This is the single most common wrong assumption about nginx.
  • File order matters only among regex blocks.

The trap, and the two-character fix

Every "nginx is ignoring my location block" report is a version of this. The block is not ignored; a regex further down matched and regex outranks a plain prefix.

Code
# Broken: the regex wins, and PNGs get proxied instead of served
location /images/ { root /var/www; }
location ~* \.png$ { proxy_pass http://app; }
# Fixed: ^~ stops the search before regex is reached
location ^~ /images/ { root /var/www; }
location ~* \.png$ { proxy_pass http://app; }
  • Reordering the file does not help here. Only `^~`, an exact match, or a narrower regex does.
  • `~` is case sensitive, `~*` is not.

Reverse proxy

Passing requests to an application, and the headers that have to travel with them.

proxy_pass and upstreams

The trailing slash, the headers, and load balancing across several backends.

The trailing slash changes the path

A URI on `proxy_pass`, even a bare slash, replaces the matched location prefix. No URI means the full original path is passed through.

Code
# Request: /api/users
location /api/ { proxy_pass http://app:3000; }
# -> http://app:3000/api/users (prefix kept)
location /api/ { proxy_pass http://app:3000/; }
# -> http://app:3000/users (prefix stripped)
  • This is the most consequential single character in an nginx config.
  • A `proxy_pass` with a URI cannot be used inside a regex location, because there is no fixed prefix to replace.

The headers an upstream actually needs

Without these the application sees nginx as the client: the wrong IP in its logs, the wrong scheme when it builds absolute URLs, and the wrong host in redirects.

Code
location /api/ {
proxy_pass http://app:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_http_version 1.1;
proxy_read_timeout 60s;
}
  • `$proxy_add_x_forwarded_for` appends rather than replaces, which is what preserves the chain through several proxies.
  • `proxy_http_version 1.1` is required for keepalive to an upstream, and for WebSockets.

WebSockets, and load balancing

The `Upgrade` and `Connection` headers are what turn a proxied HTTP request into a WebSocket. The long read timeout is what keeps an idle socket alive.

Code
upstream app {
least_conn; # or ip_hash, or default round robin
server app1:3000 max_fails=3 fail_timeout=30s;
server app2:3000;
server app3:3000 backup; # only used when the others are down
keepalive 32;
}
location /ws/ {
proxy_pass http://app;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 3600s; # or the socket dies after 60s
}
  • `keepalive 32` in the upstream needs `proxy_http_version 1.1` and an empty `Connection` header in the location to take effect.
  • `ip_hash` gives sticky sessions by client address, which breaks when everyone arrives through the same NAT gateway.

TLS and headers

Terminating HTTPS, redirecting, and the response headers worth setting.

TLS termination

A modern configuration, and the redirect that goes with it.

A current TLS server block

`fullchain.pem` rather than `cert.pem`: nginx does not build the chain for you, and a missing intermediate is the classic "works in my browser, fails in curl" bug.

Code
server {
listen 443 ssl;
http2 on; # 1.25.1+; older builds: listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers off; # let the client choose, per current guidance
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
ssl_stapling on;
ssl_stapling_verify on;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
}
  • `ssl_prefer_server_ciphers off` is current guidance for TLS 1.3, where the client ordering is trusted.
  • The `always` on `add_header` is what makes the header appear on error responses too, which is where it is most often missing.

Redirect HTTP to HTTPS

`return` is cheaper and clearer than a `rewrite`. `$host` preserves whichever name the client used, so one block serves both.

Code
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$host$request_uri;
}
  • Do not use `$server_name` here: it is the first name in the block, so www visitors would be redirected to the bare domain and lose the distinction.
  • Behind a load balancer that already terminates TLS, redirect on `$http_x_forwarded_proto` instead, or you will loop.

Performance and limits

Compression, caching headers, rate limiting, and upload sizes.

Compression and static files

Serving assets efficiently, and telling the client how long to keep them.

Compression that is worth having

`text/html` is always compressed and cannot be listed. Compressing already-compressed formats such as png, jpeg or woff2 wastes CPU and can make them slightly larger.

Code
gzip on;
gzip_vary on; # vary the cache on Accept-Encoding
gzip_min_length 1024; # below this, framing costs more than it saves
gzip_comp_level 5; # 6+ costs CPU for very little size
gzip_types text/plain text/css application/json
application/javascript text/xml application/xml
image/svg+xml;
  • `gzip_vary on` matters the moment a CDN sits in front, or it may serve a compressed body to a client that cannot read it.
  • Brotli needs a module that is not in the default build. Where a CDN is in front, let the CDN do it.

Cache headers for hashed assets

The pairing that makes a build pipeline work: fingerprinted assets cached for a year and never revalidated, with the HTML that references them never cached.

Code
location ^~ /assets/ {
root /var/www;
expires 1y;
add_header Cache-Control "public, immutable";
access_log off;
}
location = /index.html {
root /var/www;
expires -1; # always revalidate
add_header Cache-Control "no-cache";
}
  • `immutable` tells the browser not to revalidate even on a reload, which is safe only for content-hashed filenames.
  • `^~` on the assets prefix stops a later regex block from claiming these files.

Rate limiting and body size

Protecting an upstream, and the two limits that generate the most support tickets.

Rate limiting with a burst

`burst=20` allows a queue of 20 beyond the steady rate. `nodelay` serves that burst immediately instead of spacing it out, which is what real traffic looks like.

Code
# In http: a 10 MB zone holds roughly 160,000 addresses
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
location /api/ {
limit_req zone=api burst=20 nodelay;
limit_req_status 429;
proxy_pass http://app:3000;
}
  • Without `nodelay`, bursts are queued and released at exactly the rate, so a page loading 15 assets at once feels artificially slow.
  • Default `limit_req_status` is 503, which says "server problem". 429 says "you are going too fast", which is what you mean.

Upload size, in two places

The default is 1 MB, and exceeding it returns 413 before the request ever reaches your application, so the app logs show nothing at all.

Code
client_max_body_size 20m; # nginx: 413 above this
client_body_buffer_size 128k; # larger bodies go to a temp file
  • Set it in `http` for everywhere, or in the one upload `location` to keep the limit tight elsewhere.
  • The application usually has its own limit as well. Raising only the nginx one moves the failure rather than fixing it.

Running it

Reloading, reading logs, and finding out what nginx actually thinks the config is.

Commands and signals

Testing, reloading without dropping connections, and inspecting the effective config.

The four commands worth memorising

A reload starts new workers with the new config and lets old workers finish their current connections, so there is no dropped request and no downtime.

Code
Terminal window
nginx -t # syntax check, names the file and line on failure
nginx -T # check AND dump the full effective config
nginx -s reload # reload gracefully, existing connections finish
nginx -V 2>&1 | tr ' ' '\n' | grep _module # which modules this build has
Execution
Terminal window
nginx -t
Output
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
  • Always `nginx -t` before `nginx -s reload`. A reload with a broken config leaves the old one running, but in a container it means the process exits and the container restarts.
  • `nginx -V` is how you find out whether brotli or the real-IP module is compiled in, which is not something the config can tell you.

Logs, and what to put in them

`$request_time` is what the client experienced. `$upstream_response_time` is what the application took. The gap between them is nginx, the network, or a slow client body.

Code
log_format main '$remote_addr $host "$request" $status $body_bytes_sent '
'rt=$request_time urt=$upstream_response_time '
'ua="$http_user_agent"';
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log warn;
  • Those two timings side by side answer "is it us or the app" without any other tooling.
  • `error_log` at `debug` needs a build with `--with-debug`; otherwise the level is silently capped.

Was this useful?

You might also enjoy

More posts on similar topics

OpenSSL

Most OpenSSL use falls into two very different jobs. One is creating things: keys, CSRs, an internal CA. The other is answering "why does this TLS connection not work", which is where the tool earns i

#OpenSSL#TLS#SSL+5 tags
read more

Linux Networking

Every Linux box speaks the network through a small set of tools, and knowing them turns "the network is broken" into a specific, fixable answer. This cheatsheet covers the modern stack: ip for inter

#Linux networking#Ip command#Tcpdump+5 tags
read more

YAML

YAML (YAML Ain't Markup Language) is a human-friendly data serialization language widely used for configuration files, data exchange, and infrastructure-as-code. It emphasizes readability and uses ind

#YAML#Configuration#Data Serialization+6 tags
read more

jq

jq clicked for me the day I stopped thinking of it as a JSON string transformer. It is a stream of values, and every filter takes a stream in and emits a stream out. That one idea explains the parts t

#Jq#JSON#Shell+4 tags
read more

GitHub Actions

GitHub Actions runs your CI/CD directly from YAML files in .github/workflows/, and most of the job is knowing which key does what. A workflow reacts to events, splits into jobs that run on runners,

#GitHub Actions#Workflow#CI/CD+5 tags
read more

kubectl

kubectl is the command-line tool you use to talk to a Kubernetes cluster. Whatever you can do through a dashboard, you can do faster here: deploy apps, inspect resources, stream logs, run commands ins

#Kubectl#Kubernetes#K8s+5 tags
read more

6 related posts