---
title: "Nginx"
description: "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."
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/cheatsheets/nginx
---

# Nginx

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.

_How nginx chooses a location block_

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.

_What is left for nginx behind an ALB_

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.

**Keywords:** context, http, server, location

#### The four contexts you write in

```nginx
# 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;
    }
  }
}
```

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.

- 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

```bash
/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
```

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.

- 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.

**Best practices:**

- One server block per file, named after the host it serves.
- Set shared directives once in `http` rather than repeating them per server.

**Common errors:**

- **"directive is not allowed here"**: The directive is legal, the context is not. `proxy_pass` cannot go in `server`, only in `location`. The message names the file and line.
- **Config changes have no effect**: Either the file was never included (check the path and the `.conf` suffix) or nginx was not reloaded. `nginx -T` prints the full config as nginx sees it, includes resolved.

**Advanced notes:**

- **nginx -T is the debugging command:** `nginx -t` tests the syntax. `nginx -T` tests it and then dumps the entire effective configuration with every `include` expanded. When a setting is not taking effect, `nginx -T | grep -n <directive>` tells you in one step whether nginx is even reading what you edited.

### Server blocks and name matching

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

**Keywords:** server_name, virtual host, default_server, listen

#### A minimal pair of server blocks

```nginx
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;
}
```

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.

- 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
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
```

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.

- 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.

**Best practices:**

- Always define an explicit `default_server` that returns 444 or 421, so unmatched traffic has a deliberate answer.
- List the bare domain and the www form in the same `server_name`, then redirect one to the other in a separate block.

**Common errors:**

- **Requests reach the wrong site**: Some other block is the default for that port. `nginx -T | grep -n default_server` shows which, and there can only be one per listen address.
- **"conflicting server name ... ignored"**: The same name is declared in two server blocks on the same port. Nginx keeps the first and warns about the second.

**Advanced notes:**

- **HTTPS and the default server:** For TLS, name matching happens after the handshake, so the default server's certificate is what a client sees when SNI does not match anything. That is why probing an HTTPS host by IP shows an unexpected certificate: you are meeting the default server, not a misconfigured one.

## 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.

**Keywords:** location, prefix, regex, matching

#### The five steps, in order

```nginx
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
```

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 `^~`.

- 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

```nginx
# 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; }
```

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.

- Reordering the file does not help here. Only `^~`, an exact match, or a narrower regex does.
- `~` is case sensitive, `~*` is not.

**Best practices:**

- Use `^~` for any static-file prefix that sits alongside a catch-all regex.
- Keep regex locations few and specific. They are tried in order for every request that gets that far.

**Common errors:**

- **A location block appears to be ignored**: A regex block matched first. Add `^~` to the prefix, or make the regex narrower.
- **Adding a trailing slash changes the behaviour of proxy_pass**: That is deliberate and important. See the reverse-proxy section below.

**Advanced notes:**

- **try_files, and the loop that 500s:** `try_files $uri $uri/ /index.html;` is the standard single-page-app fallback. Written as `try_files $uri $uri/ /index.html?$args;` inside a location that also matches `/index.html`, it can recurse and nginx will stop it with a 500 and "rewrite or internal redirection cycle" in the error log. Point the final fallback at a named location (`@app`) when the fallback would re-enter the same block.

## 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.

**Keywords:** proxy_pass, upstream, headers, load balancing

#### The trailing slash changes the path

```nginx
# 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)
```

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

- 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

```nginx
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;
}
```

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.

- `$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

```nginx
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
}
```

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.

- `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.

**Best practices:**

- Set the four forwarding headers on every proxy location, or set them once in a snippet and `include` it.
- Give upstream servers `max_fails` and `fail_timeout` so a dead backend is taken out of rotation rather than retried forever.

**Common errors:**

- **502 Bad Gateway**: Nginx reached the upstream and got nothing usable. Check the app is listening on the address nginx names, and read `error.log`: "connect() failed" is refused, "upstream prematurely closed" is the app crashing mid-response.
- **504 Gateway Timeout**: The upstream accepted the connection and did not answer within `proxy_read_timeout`. Raise it only after confirming the app is not simply slow.
- **WebSocket connects then drops after about a minute**: `proxy_read_timeout` defaults to 60 seconds and an idle socket sends nothing. Raise it for the WebSocket location only.

**Advanced notes:**

- **DNS resolution is done once, at startup:** A `proxy_pass http://app:3000` with a literal host name resolves at load time and caches forever. In Kubernetes or ECS, where a service address can change, that means nginx keeps sending traffic to an address that no longer exists. Fix it with a `resolver` directive and a variable: `resolver 10.0.0.2 valid=10s; set $upstream http://app:3000; proxy_pass $upstream;`. Using a variable forces re-resolution.

## TLS and headers

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

### TLS termination

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

**Keywords:** ssl, tls, https, certificate

#### A current TLS server block

```nginx
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;
}
```

`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.

- `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

```nginx
server {
  listen 80;
  server_name example.com www.example.com;
  return 301 https://$host$request_uri;
}
```

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

- 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.

**Best practices:**

- Use `fullchain.pem`, always, and verify with `openssl s_client -connect host:443 -servername host` that the chain is complete.
- Set security headers once in the `http` context, and remember that any `add_header` in a location discards the inherited set.

**Common errors:**

- **Works in a browser, fails in curl or a Java client**: A missing intermediate certificate. Browsers cache intermediates from other sites and paper over it. Use `fullchain.pem`.
- **Redirect loop behind a load balancer**: The load balancer terminates TLS and forwards on HTTP, so `$scheme` is always http and the redirect fires forever. Test `$http_x_forwarded_proto` instead.
- **Security headers missing on 404 responses**: Add `always` to `add_header`. Without it the header is only set for a small set of success statuses.

**Advanced notes:**

- **Header inheritance is replacement, not merge:** If `http` sets three security headers and one `location` sets a fourth, that location sends only the fourth. Nginx replaces the whole `add_header` set at the level that defines one. The usual fix is a snippet file `include`d in both places, since there is no merge syntax.

## 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.

**Keywords:** gzip, brotli, cache, expires

#### Compression that is worth having

```nginx
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;
```

`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.

- `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

```nginx
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";
}
```

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.

- `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.

**Best practices:**

- Cache fingerprinted assets for a year and the entry HTML not at all.
- Turn `access_log off` for static assets: it is most of the log volume and none of the signal.

**Common errors:**

- **A CDN serves a gzipped response to a client that did not ask for one**: Set `gzip_vary on` so `Vary: Accept-Encoding` is sent and the cache keys on it.
- **Users keep an old build after a deploy**: The HTML is being cached. Fingerprinted assets can cache forever, but the document that names them must revalidate.

**Advanced notes:**

- **sendfile, tcp_nopush and tcp_nodelay:** `sendfile on` copies a file to the socket in the kernel, without passing through nginx memory. `tcp_nopush on` then fills whole packets before sending, and `tcp_nodelay on` disables Nagle for the last partial packet. The three together are the standard static-file trio: full packets for the body, no delay on the tail.

### Rate limiting and body size

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

**Keywords:** limit_req, rate limit, client_max_body_size, burst

#### Rate limiting with a burst

```nginx
# 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;
}
```

`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.

- 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

```nginx
client_max_body_size 20m;      # nginx: 413 above this
client_body_buffer_size 128k;  # larger bodies go to a temp file
```

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.

- 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.

**Best practices:**

- Rate limit by `$binary_remote_addr`, not `$remote_addr`: it stores 4 or 16 bytes instead of a string.
- Return 429 rather than 503 so clients and monitoring can tell throttling from failure.

**Common errors:**

- **413 Request Entity Too Large on upload**: `client_max_body_size` is 1 MB by default. Raise it in nginx and check the application's own limit too.
- **Rate limiting throttles everyone at once**: Behind a load balancer, `$remote_addr` is the balancer. Configure `set_real_ip_from` with the VPC CIDR and `real_ip_header X-Forwarded-For`, or every client counts as one.

**Advanced notes:**

- **Test the limit before trusting it:** A rate limit that is never exercised is a guess. `for i in $(seq 1 40); do curl -o /dev/null -s -w "%{http_code} " localhost/api/; done` shows exactly where the 429s begin, and whether `burst` behaves as you expected. Doing this on a staging host takes a minute and has saved me from shipping a limit an order of magnitude off.

## 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.

**Keywords:** reload, nginx -t, signal, logs

#### The four commands worth memorising

```bash
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
```

_exec_
```bash
nginx -t
```

_output_
```text
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
```

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.

- 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

```nginx
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;
```

`$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.

- 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.

**Best practices:**

- Put `$request_time` and `$upstream_response_time` in the access log from day one.
- Run `nginx -t` in CI against the rendered config, so a bad template fails the pipeline rather than the deploy.

**Common errors:**

- **Reload appears to succeed but behaviour is unchanged**: Nginx is reading a different file than you edited. `nginx -T | grep -n <your directive>` settles it immediately.
- **"bind() to 0.0.0.0:80 failed (98: Address already in use)"**: Another process holds the port, often an old nginx master. `ss -tlnp | grep :80` names it.

**Advanced notes:**

- **Reload versus restart in a container:** In Kubernetes there is usually no one to send `-s reload` to. The common patterns are a sidecar that watches a mounted ConfigMap and signals the master, or simply rolling the pods, which is a restart rather than a reload. A restart drops in-flight connections, so it needs a `preStop` sleep and a readiness probe that fails first, the same graceful-shutdown ordering any server needs.
