On this page

Nginx Cheat Sheet

Quick reference for Nginx server blocks, locations, reverse proxy, SSL/TLS configuration, rate limiting, caching, and common recipes.


Commands

CommandDescription
nginxStart Nginx
nginx -s stopFast shutdown
nginx -s quitGraceful shutdown
nginx -s reloadReload configuration
nginx -s reopenReopen log files
nginx -tTest configuration
nginx -TTest and dump full config
nginx -VShow version and build options
systemctl status nginxCheck service status
systemctl restart nginxRestart service

TIP

Always run nginx -t before nginx -s reload to catch syntax errors.

# Config in one go: test, then reload only if valid
sudo nginx -t && sudo systemctl reload nginx

# Find which file sets a directive
sudo nginx -T 2>/dev/null | grep -n "client_max_body_size"

# Check which modules were compiled in (http_v3_module, realip, etc.)
nginx -V 2>&1 | tr ' ' '\n' | grep -- --with

Server Blocks

Basic Server Block

server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;
    root /var/www/example;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

Multiple Sites

# /etc/nginx/sites-available/site-a.conf
server {
    listen 80;
    server_name a.example.com;
    root /var/www/site-a;
}

# /etc/nginx/sites-available/site-b.conf
server {
    listen 80;
    server_name b.example.com;
    root /var/www/site-b;
}

Default / Catch-All Server

server {
    listen 80 default_server;
    server_name _;
    return 444;                  # Close connection (no response)
}

# HTTPS catch-all: refuse the TLS handshake for unknown hosts (1.19.4+, no cert needed)
server {
    listen 443 ssl default_server;
    server_name _;
    ssl_reject_handshake on;
}

Without an explicit default_server, the first server block for a listen address handles requests for unknown hosts. server_name _ is just an invalid name, not a wildcard.


Location Blocks

Location Match Priority

ModifierTypeExamplePriority
=Exact match= /favicon.ico1 (highest)
^~Prefix (no regex after)^~ /static/2
~Regex (case-sensitive)~ \.php$3
~*Regex (case-insensitive)~* \.(jpg|png)$3
(none)Prefix/api/4 (lowest)

How nginx actually picks a location:

  1. An = exact match wins immediately.
  2. Otherwise nginx finds the longest matching prefix (with or without ^~). If that longest prefix has ^~, it is used.
  3. Otherwise regex locations (~, ~*) are tried in the order they appear in the file; the first match wins.
  4. If no regex matches, the longest prefix from step 2 is used.

So the order of prefix locations in the file does not matter, but the order of regex locations does.

Location Examples

# Exact match
location = /health {
    default_type text/plain;     # sets Content-Type; add_header would add a second one
    return 200 "ok\n";
}

# Prefix match
location /api/ {
    proxy_pass http://backend;
}

# Regex match (images)
location ~* \.(jpg|jpeg|png|gif|svg|webp)$ {
    expires 30d;
    add_header Cache-Control "public, immutable";
}

# Static files (stop searching after match)
location ^~ /static/ {
    alias /var/www/static/;
    expires max;
}

# Named location (internal redirect)
location @fallback {
    proxy_pass http://backend;
}

location / {
    try_files $uri $uri/ @fallback;
}

Reverse Proxy

Basic Reverse Proxy

server {
    listen 80;
    server_name app.example.com;

    location / {
        proxy_pass http://127.0.0.1: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;
    }
}

Common Proxy Settings

client_max_body_size 50m;          # default 1m; larger uploads get 413
proxy_buffering off;               # for Server-Sent Events / streaming responses
proxy_request_buffering off;       # stream large uploads straight to the backend
proxy_redirect off;                # don't rewrite Location headers from the backend

# HTTPS upstream: send SNI and verify the backend certificate
proxy_pass https://api.internal;
proxy_ssl_server_name on;
proxy_ssl_verify on;
proxy_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt;

Real Client IP behind a Load Balancer / CDN

# ngx_http_realip_module: trust X-Forwarded-For only from your LB's addresses
set_real_ip_from 10.0.0.0/8;
set_real_ip_from 2001:db8::/32;
real_ip_header X-Forwarded-For;
real_ip_recursive on;               # skip trusted proxies, take the first untrusted IP
# $remote_addr is now the client IP (logs, allow/deny, limit_req all use it)

Upstream (Load Balancing)

upstream backend {
    least_conn;                  # Load balancing method
    server 10.0.0.1:3000 weight=3;
    server 10.0.0.2:3000;
    server 10.0.0.3:3000 backup;
    server 10.0.0.4:3000 max_fails=3 fail_timeout=30s;   # passive health check
    keepalive 32;                # Connection pool
}

# Re-resolve a DNS name when its records change (open source nginx 1.27.3+)
upstream api {
    zone api 64k;                # shared memory zone, required for "resolve"
    resolver 10.0.0.2 valid=30s;
    server api.internal:8080 resolve;
}

server {
    location / {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
    }
}

Load Balancing Methods

DirectiveDescription
(default)Round robin
least_connFewest active connections
ip_hashSticky sessions by client IP
hash $request_uriHash-based (remaps most keys when servers change)
hash $request_uri consistentConsistent (ketama) hashing: minimal remapping
random two least_connRandom pick, prefer least conn

WebSocket Proxy

location /ws/ {
    proxy_pass http://backend;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $host;
    proxy_read_timeout 86400s;
    proxy_send_timeout 86400s;
}

If the same location serves both WebSocket and normal HTTP, set Connection from a map so plain requests keep keepalive:

# http block
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      "";
}

# location
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;

Proxy Timeouts

location /api/ {
    proxy_pass http://backend;
    proxy_connect_timeout 5s;
    proxy_send_timeout 30s;
    proxy_read_timeout 30s;
    proxy_next_upstream error timeout http_502 http_503;
    proxy_next_upstream_tries 2;
}

SSL/TLS Configuration

HTTPS Server

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    http2 on;                    # 1.25.1+; "listen ... ssl http2" is deprecated
    server_name example.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    # Modern TLS configuration
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;

    # OCSP stapling: only for CAs that still run OCSP. Let's Encrypt shut down
    # its OCSP service in 2025, so with LE certs nginx just logs
    # "no OCSP responder URL in the certificate"; leave these off for LE.
    ssl_stapling on;
    ssl_stapling_verify on;
    ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem;

    # Session caching
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 1d;
    ssl_session_tickets off;

    # HSTS
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
}

ssl_ciphers applies to TLS 1.2 only; TLS 1.3 suites are fixed by OpenSSL defaults. Only add preload to HSTS once every subdomain serves HTTPS: removal from browser preload lists takes months.

HTTP/2 and HTTP/3 (QUIC)

server {
    # HTTP/1.1 + HTTP/2 over TCP
    listen 443 ssl;
    listen [::]:443 ssl;
    http2 on;

    # HTTP/3 over UDP (nginx 1.25.0+, built --with-http_v3_module)
    listen 443 quic reuseport;           # "reuseport" only once per address:port across all servers
    listen [::]:443 quic reuseport;
    http3 on;                            # default is on for quic listeners

    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;       # QUIC always uses TLS 1.3; 1.2 is for TCP clients

    # Tell browsers HTTP/3 is available (they first connect over TCP)
    add_header Alt-Svc 'h3=":443"; ma=86400' always;

    quic_retry on;                       # address validation, helps against spoofed floods
    quic_gso on;                         # segmentation offload on Linux, cheaper sends
    ssl_early_data on;                   # 0-RTT; replayable, so only for idempotent requests
    proxy_set_header Early-Data $ssl_early_data;
}
DirectivePurpose
http2 on;Enable HTTP/2 per server (replaces listen ... http2)
http2_max_concurrent_streams 128;Streams per connection (default 128)
listen 443 quic;Accept QUIC on UDP 443
http3 on; / http3_hq on;HTTP/3 / HTTP/0.9-over-QUIC (interop testing)
quic_retry on;Send Retry packets to validate client addresses
quic_host_key file;Shared key so tokens survive reloads and work across servers

HTTP/3 checklist

  • Open UDP 443 in the firewall and security groups (TCP 443 alone is not enough).
  • Browsers only switch to h3 after seeing Alt-Svc, so the first request is always TCP.
  • HTTP/2 server push was removed in 1.25.1; http2_push no longer exists.
  • Test with curl --http3 -I https://example.com (curl built with HTTP/3) or the browser dev tools Protocol column.

HTTP to HTTPS Redirect

server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;
    return 301 https://example.com$request_uri;
}

Let's Encrypt with Certbot

# Install
sudo apt install certbot python3-certbot-nginx

# Obtain certificate
sudo certbot --nginx -d example.com -d www.example.com

# Auto-renewal test
sudo certbot renew --dry-run

# Renewal cron (usually auto-configured)
# 0 0,12 * * * certbot renew --quiet

# Most packages install a systemd timer instead
systemctl list-timers | grep certbot

# Reload nginx after each successful renewal
sudo certbot renew --deploy-hook "systemctl reload nginx"

Rate Limiting

# Define rate limit zone (in http block)
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=login:10m rate=1r/s;

server {
    # Apply rate limit
    location /api/ {
        limit_req zone=api burst=20 nodelay;
        limit_req_status 429;
        proxy_pass http://backend;
    }

    # Strict rate limit for login
    location /auth/login {
        limit_req zone=login burst=5;
        limit_req_status 429;
        proxy_pass http://backend;
    }
}
SettingBehaviour with rate=10r/s
no burstAny request faster than 1 per 100 ms is rejected
burst=20Up to 20 excess requests are queued and released at 10 r/s (adds latency)
burst=20 nodelay20 excess requests are served immediately; the slots refill at 10 r/s
burst=20 delay=8First 8 excess served immediately, the rest delayed (1.15.7+)

Default rejection status is 503; set limit_req_status 429. Test without enforcing with limit_req_dry_run on;.

Connection Limiting

# Define connection limit zone
limit_conn_zone $binary_remote_addr zone=addr:10m;

server {
    location /download/ {
        limit_conn addr 5;           # Max 5 concurrent per IP
        limit_rate 500k;             # Throttle to 500KB/s
        limit_rate_after 10m;        # Full speed for first 10MB
    }
}

Caching

Proxy Cache

# Define cache zone (in http block)
proxy_cache_path /var/cache/nginx
    levels=1:2
    keys_zone=app_cache:10m
    max_size=1g
    inactive=60m
    use_temp_path=off;

server {
    location / {
        proxy_pass http://backend;
        proxy_cache app_cache;
        proxy_cache_valid 200 10m;
        proxy_cache_valid 404 1m;
        proxy_cache_use_stale error timeout updating http_500 http_502 http_503;
        proxy_cache_lock on;

        add_header X-Cache-Status $upstream_cache_status;
    }

    # Bypass cache
    location /api/ {
        proxy_pass http://backend;
        proxy_cache app_cache;
        proxy_cache_bypass $http_cache_control;
        proxy_no_cache $arg_nocache;
    }
}

Static File Caching (Browser)

location ~* \.(css|js|woff2|woff|ttf)$ {
    expires 1y;
    add_header Cache-Control "public, immutable";
    access_log off;
}

location ~* \.(jpg|jpeg|png|gif|svg|webp|ico)$ {
    expires 30d;
    add_header Cache-Control "public";
    access_log off;
}

location ~* \.(html)$ {
    expires 1h;
    add_header Cache-Control "public, must-revalidate";
}

Security Headers

# Add to server or http block
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "0" always;   # legacy XSS auditor is gone from browsers; "1; mode=block" could itself cause leaks, so disable it and rely on CSP
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;

# Hide Nginx version
server_tokens off;

X-Frame-Options is superseded by CSP frame-ancestors 'self'; sending both is fine.

add_header inheritance

add_header directives are inherited from the parent level only if the current level defines none. Since nginx 1.29.3 you can write add_header_inherit merge; in the child block to keep the parent headers and add your own. On older versions, repeat the headers (an include security-headers.conf; file helps).


Common Recipes

Redirect www to non-www

server {
    listen 80;
    listen 443 ssl;
    http2 on;
    server_name www.example.com;
    # needs ssl_certificate / ssl_certificate_key covering www.example.com
    return 301 https://example.com$request_uri;
}

Trailing Slash Redirect

# Add trailing slash
rewrite ^([^.\?]*[^/])$ $1/ permanent;

# Remove trailing slash
rewrite ^/(.*)/$ /$1 permanent;

map: Variables from Lookups

# http block: allow a list of CORS origins
map $http_origin $cors_origin {
    default                         "";
    "https://app.example.com"       $http_origin;
    "~^https://[a-z0-9-]+\.example\.com$" $http_origin;
}

# then in a location
add_header Access-Control-Allow-Origin $cors_origin always;
add_header Vary Origin always;

An empty value makes add_header send nothing, so unknown origins get no CORS header.

CORS Headers

location /api/ {
    # Simple CORS
    add_header Access-Control-Allow-Origin "https://app.example.com" always;
    add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS" always;
    add_header Access-Control-Allow-Headers "Authorization, Content-Type" always;
    add_header Access-Control-Max-Age 86400 always;

    # Handle preflight
    if ($request_method = OPTIONS) {
        return 204;
    }

    proxy_pass http://backend;
}

Custom Error Pages

server {
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;

    location = /404.html {
        root /var/www/errors;
        internal;
    }

    location = /50x.html {
        root /var/www/errors;
        internal;
    }
}

Basic Auth

# Create password file
sudo apt install apache2-utils
sudo htpasswd -c /etc/nginx/.htpasswd admin
location /admin/ {
    auth_basic "Restricted";
    auth_basic_user_file /etc/nginx/.htpasswd;
    proxy_pass http://backend;
}

IP Allowlist / Denylist

location /admin/ {
    allow 10.0.0.0/8;
    allow 192.168.1.0/24;
    deny all;
    proxy_pass http://backend;
}

Gzip Compression

gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 4;
gzip_min_length 256;
gzip_types
    text/plain
    text/css
    text/xml
    text/javascript
    application/json
    application/javascript
    application/xml
    application/rss+xml
    image/svg+xml;

SPA (Single Page Application)

server {
    listen 80;
    server_name app.example.com;
    root /var/www/app/dist;
    index index.html;

    location / {
        try_files $uri $uri/ /index.html;
    }

    location /api/ {
        proxy_pass http://backend;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|svg|ico|woff2)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
}

Logging

# Custom log format
log_format main '$remote_addr - $remote_user [$time_local] '
                '"$request" $status $body_bytes_sent '
                '"$http_referer" "$http_user_agent" '
                '$request_time $upstream_response_time';

# JSON log format
log_format json escape=json '{'
    '"time":"$time_iso8601",'
    '"remote_addr":"$remote_addr",'
    '"method":"$request_method",'
    '"uri":"$request_uri",'
    '"status":$status,'
    '"body_bytes_sent":$body_bytes_sent,'
    '"request_time":$request_time,'
    '"upstream_time":"$upstream_response_time"'
'}';

server {
    access_log /var/log/nginx/access.log json;
    error_log /var/log/nginx/error.log warn;

    # Disable logging for health checks
    location = /health {
        access_log off;
        return 200 "ok\n";
    }
}

Common Variables

VariableDescription
$hostRequest Host header
$remote_addrClient IP address
$request_uriFull original URI with args
$uriNormalized URI (no args)
$argsQuery string
$schemehttp or https
$request_methodGET, POST, etc.
$statusResponse status code
$request_timeRequest processing time (seconds)
$upstream_response_timeBackend response time
$upstream_cache_statusHIT, MISS, BYPASS, etc.
$http_<header>Any request header (lowercase, - to _)
$arg_<name>Query parameter name
$cookie_<name>Cookie name
$server_nameName of the server block that matched
$request_idRandom 32-hex request ID (pass it on as X-Request-ID)
$ssl_protocol / $ssl_cipherNegotiated TLS version / cipher
$server_protocolHTTP/1.1, HTTP/2.0, HTTP/3.0
$upstream_addrWhich backend served the request

When to Use X vs Y

DecisionChoice AChoice BUse A WhenUse B When
root vs aliasrootaliasURI path maps to filesystemURI prefix differs from path
return vs rewritereturnrewriteSimple redirect (faster)Pattern-based URL transform
proxy_pass trailing /With /Without /Strip location prefixKeep full URI path
Load balancingleast_connip_hashUniform distributionSession persistence
Rate limitnodelay(default)Reject excess immediatelyQueue excess requests
CacheProxy cacheBrowser cacheDynamic content, reduce backend loadStatic assets

Test Yourself
  1. What command tests Nginx configuration for syntax errors? nginx -t

  2. Which location modifier has the highest priority? = (exact match).

  3. What headers must you set to proxy WebSocket connections? Upgrade $http_upgrade and Connection "upgrade"

  4. How do you redirect all HTTP traffic to HTTPS? return 301 https://$host$request_uri; in a server block listening on port 80.

  5. What directive defines a rate limit zone in the http block? limit_req_zone $binary_remote_addr zone=name:10m rate=10r/s;

  6. What is the difference between root and alias? root appends the URI path to the root path; alias replaces the matched location prefix.

  7. How do you hide the Nginx version from response headers? server_tokens off;

  8. What load balancing method provides sticky sessions by client IP? ip_hash

  9. What does try_files $uri $uri/ /index.html do in an SPA configuration? It tries the requested file, then a directory, then falls back to index.html for client-side routing.

  10. What proxy header passes the original client IP to the backend? proxy_set_header X-Real-IP $remote_addr;

Common Gotchas

  • Trailing slash in proxy_pass changes behavior. proxy_pass http://backend/ strips the location prefix; proxy_pass http://backend keeps the full URI. Getting this wrong breaks all your routes.
  • add_header in a child block removes parent headers. If you set add_header in a location block, all add_header directives from the server block are lost. You must repeat them.
  • Forgetting nginx -t before nginx -s reload. On reload with a broken config the master process logs the error and keeps running the old config, so the change silently doesn't apply. systemctl restart with a broken config is worse: nginx stops and does not come back. Always test first.
  • Applying rate limits without burst. Without burst, legitimate traffic spikes get 429 errors. Set burst=20 nodelay to handle short bursts.
  • listen 443 ssl http2 in copied configs. Deprecated since 1.25.1 and logs a warning; use listen 443 ssl; plus http2 on;.
  • proxy_pass http://name resolves DNS once at startup. If the backend's IP changes (cloud LBs, containers), nginx keeps the old IP. Use an upstream with resolve (1.27.3+) or a variable in proxy_pass with a resolver.
  • if inside location. Only return and rewrite ... last are reliably safe in it ("if is evil"). Prefer map, try_files or separate locations.
  • alias with a regex location or a missing trailing slash. location /static/ { alias /var/www/static/; }: both or neither should end in /, or paths get mangled (/var/www/staticfile.css).
  • $remote_addr is the load balancer. Behind an LB or CDN, configure the realip module, or rate limits and allowlists apply to the LB's IP.

One-Liner Summary

Nginx is a high-performance web server and reverse proxy -- master location blocks, upstream load balancing, SSL termination, and rate limiting to serve and protect any web application.