Nginx Cheatsheet

This cheatsheet provides a comprehensive and practical reference for Nginx commands and configuration. It covers basic commands, configuration files, server blocks, location & rewrite, security, logs, command combos, and more. Use it to boost your productivity in web server management and automation.

109 directives
Commands

Service Management

sudo systemctl start nginx

Start Nginx service

sudo systemctl stop nginx

Stop Nginx service

sudo systemctl restart nginx

Restart Nginx service

sudo systemctl reload nginx

Reload configuration

sudo systemctl status nginx

Check service status

sudo systemctl enable nginx

Enable at boot

Commands

Configuration

nginx -t

Test configuration syntax

nginx -T

Test and dump configuration

nginx -V

Show version and build options

nginx -s reload

Reload configuration

nginx -s stop

Fast shutdown

nginx -s quit

Graceful shutdown

Server Blocks

Basic Server Block

server { listen 80; server_name example.com; root /var/www/html; }

Basic HTTP server

listen 80 default_server;

Default server for port 80

listen [::]:80;

Listen on IPv6

server_name example.com www.example.com;

Multiple server names

server_name *.example.com;

Wildcard server name

server_name ~^www\d+\.example\.com$;

Regex server name

Server Blocks

HTTPS Server

listen 443 ssl http2;

HTTPS with HTTP/2

ssl_certificate /path/to/cert.pem;

SSL certificate path

ssl_certificate_key /path/to/key.pem;

SSL key path

ssl_protocols TLSv1.2 TLSv1.3;

Allowed TLS versions

ssl_prefer_server_ciphers on;

Prefer server ciphers

ssl_session_cache shared:SSL:10m;

SSL session cache

Location

Location Matching

location / { ... }

Prefix match (lowest priority)

location = /exact { ... }

Exact match (highest priority)

location ^~ /images/ { ... }

Prefix match, stop regex search

location ~ \.php$ { ... }

Case-sensitive regex

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

Case-insensitive regex

location @named { ... }

Named location

💡 Priority: = > ^~ > ~ or ~* > prefix

Location

Common Directives

root /var/www/html;

Document root

alias /var/www/files/;

Replace location path

index index.html index.php;

Default index files

try_files $uri $uri/ /index.php?$query_string;

Try files in order

autoindex on;

Enable directory listing

return 301 https://$host$request_uri;

Redirect to HTTPS

Proxy

Reverse Proxy

proxy_pass http://localhost:3000;

Proxy to backend

proxy_set_header Host $host;

Pass original host

proxy_set_header X-Real-IP $remote_addr;

Pass client IP

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

Forward chain

proxy_set_header X-Forwarded-Proto $scheme;

Forward protocol

proxy_http_version 1.1;

Use HTTP/1.1

Proxy

WebSocket Proxy

proxy_set_header Upgrade $http_upgrade;

WebSocket upgrade header

proxy_set_header Connection "upgrade";

WebSocket connection

proxy_read_timeout 86400;

Long timeout for WS

Proxy

Load Balancing

upstream backend { server 127.0.0.1:8001; server 127.0.0.1:8002; }

Basic upstream

upstream backend { least_conn; server ...; }

Least connections

upstream backend { ip_hash; server ...; }

IP hash (sticky)

server 127.0.0.1:8001 weight=3;

Weighted server

server 127.0.0.1:8001 backup;

Backup server

server 127.0.0.1:8001 down;

Mark server down

Security

Security Headers

add_header X-Frame-Options "SAMEORIGIN" always;

Prevent clickjacking

add_header X-Content-Type-Options "nosniff" always;

Prevent MIME sniffing

add_header X-XSS-Protection "1; mode=block" always;

XSS protection

add_header Strict-Transport-Security "max-age=31536000" always;

HSTS header

add_header Content-Security-Policy "default-src 'self'" always;

CSP header

add_header Referrer-Policy "strict-origin-when-cross-origin" always;

Referrer policy

Security

Access Control

allow 192.168.1.0/24;

Allow IP range

deny all;

Deny all others

auth_basic "Restricted";

Enable basic auth

auth_basic_user_file /etc/nginx/.htpasswd;

Password file

satisfy any;

Allow OR deny rules

Security

Rate Limiting

limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;

Define rate limit zone

limit_req zone=one burst=5 nodelay;

Apply rate limit

limit_conn_zone $binary_remote_addr zone=addr:10m;

Connection limit zone

limit_conn addr 10;

Max 10 connections per IP

Performance

Caching

proxy_cache_path /tmp/cache levels=1:2 keys_zone=my_cache:10m;

Define cache path

proxy_cache my_cache;

Enable proxy cache

proxy_cache_valid 200 60m;

Cache 200 responses for 60m

proxy_cache_use_stale error timeout;

Serve stale on error

add_header X-Cache-Status $upstream_cache_status;

Show cache status

Performance

Browser Caching

expires 30d;

Expire in 30 days

expires max;

Maximum expiry

add_header Cache-Control "public, no-transform";

Cache control header

etag on;

Enable ETag

Performance

Compression

gzip on;

Enable gzip

gzip_vary on;

Add Vary header

gzip_min_length 1000;

Min size to compress

gzip_types text/plain text/css application/json application/javascript;

Types to compress

gzip_comp_level 6;

Compression level (1-9)

Performance

Optimization

sendfile on;

Enable sendfile

tcp_nopush on;

Optimize packet sending

tcp_nodelay on;

Disable Nagle's algorithm

keepalive_timeout 65;

Keep-alive timeout

client_max_body_size 100M;

Max upload size

Logging

Log Configuration

access_log /var/log/nginx/access.log;

Access log path

error_log /var/log/nginx/error.log warn;

Error log with level

access_log off;

Disable access log

access_log /var/log/nginx/access.log combined buffer=512k flush=1m;

Buffered logging

Logging

Custom Log Format

log_format main '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent';

Define log format

log_format json escape=json '{"time":"$time_iso8601","ip":"$remote_addr"}';

JSON log format

access_log /var/log/nginx/access.log main;

Use custom format

Variables

Request Variables

$host

Host from request line or Host header

$uri

Current URI (normalized)

$request_uri

Original request URI with args

$args / $query_string

Query string

$request_method

HTTP method (GET, POST, etc.)

$scheme

Request scheme (http/https)

Variables

Client Variables

$remote_addr

Client IP address

$remote_port

Client port

$http_user_agent

User-Agent header

$http_referer

Referer header

$http_cookie

Cookie header

$http_x_forwarded_for

X-Forwarded-For header

Variables

Response Variables

$status

Response status code

$body_bytes_sent

Bytes sent to client

$request_time

Request processing time

$upstream_response_time

Upstream response time

$upstream_cache_status

Cache status (HIT/MISS)

Quick Reference

Test config:

nginx -t

Reload:

nginx -s reload

Config path:

/etc/nginx/nginx.conf

Sites:

/etc/nginx/sites-enabled/

Categories

  • Basic Commands

    Start, stop, reload, test, and manage Nginx service.

  • Configuration Files

    Main config, includes, and site-specific configuration files.

  • Server Block Examples

    Common server block (virtual host) configuration patterns.

  • Location & Rewrite

    Location matching, URL rewriting, directory listing, and try_files.

  • Security & Optimization

    Headers, limits, access control, and performance tuning.

  • Logs & Monitoring

    Log files, log levels, and real-time monitoring.

  • Command Combos

    Powerful multi-step workflows and advanced usage patterns for real-world scenarios.

Features

  • Quick search functionality
  • Organized by categories
  • Clear command descriptions
  • Common and advanced use cases covered
  • Easy to copy commands
  • Responsive design
  • Perfect for quick reference