Cheatsheet: Nginx

Last updated 2026-09-29

Config File Structure

Minimal server block structure

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

        location / {
            root /var/www/html;
            index index.html;
        }
    }
}

Default config file locations

/etc/nginx/nginx.conf
/etc/nginx/sites-available/ + sites-enabled/ (Debian/Ubuntu)
/etc/nginx/conf.d/*.conf (RHEL/CentOS + Docker default)

Include additional config files

include /etc/nginx/conf.d/*.conf;

Location Block Matching

Exact match (highest precedence)

location = /login { ... }

Prefix match that skips regex checking

location ^~ /static/ { ... }

Case-sensitive / case-insensitive regex match

location ~ \.php$ { ... }
location ~* \.(jpg|png|gif)$ { ... }

Plain prefix match (longest wins, checked last)

location /api/ { ... }

Named location (only reachable via internal redirect, e.g. error_page/try_files)

location @fallback { ... }

Reverse Proxy & Load Balancing

Proxy requests to an upstream server

location /api/ {
    proxy_pass http://127.0.0.1:3000;
}

Preserve the original Host header and client IP

proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

Define an upstream group of servers

upstream backend {
    server 10.0.0.1:3000;
    server 10.0.0.2:3000;
}

Load-balance by least active connections

upstream backend {
    least_conn;
    server 10.0.0.1:3000;
    server 10.0.0.2:3000;
}

Sticky sessions by client IP

upstream backend {
    ip_hash;
    server 10.0.0.1:3000;
    server 10.0.0.2:3000;
}

Mark a server as backup (only used if others are down)

server 10.0.0.3:3000 backup;

TLS / SSL

Listen for HTTPS and specify certificate/key

listen 443 ssl;
ssl_certificate /etc/nginx/ssl/fullchain.pem;
ssl_certificate_key /etc/nginx/ssl/privkey.pem;

Redirect all HTTP traffic to HTTPS

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

Restrict to modern TLS versions

ssl_protocols TLSv1.2 TLSv1.3;

Test the config after certificate changes, then reload

nginx -t && nginx -s reload

Gzip Compression

Enable gzip and list the MIME types to compress

gzip on;
gzip_types text/css application/javascript application/json;

Only compress responses above a minimum size

gzip_min_length 256;

Compress responses even when Nginx is proxying them

gzip_proxied any;

CLI & Process Management

Test config syntax without applying it

nginx -t

Reload config gracefully (no dropped connections)

nginx -s reload

Stop immediately (fast shutdown, drops connections)

nginx -s stop

Quit gracefully (finishes in-flight requests)

nginx -s quit

Show version and compiled-in modules

nginx -V

Tail the default access/error logs

tail -f /var/log/nginx/access.log
tail -f /var/log/nginx/error.log

FAQ