Built for developers, by XinhND

v2.1.0

Ready

Nginx Cheat Sheet

Complete reference guide for Nginx with interactive examples and live playground links

Basic Configuration

Main Configuration

Basic Nginx configuration structure

Nginx
# Main nginx.conf
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

events {
    worker_connections 1024;
    multi_accept on;
    use epoll;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';
    
    access_log /var/log/nginx/access.log main;
    
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    
    include /etc/nginx/conf.d/*.conf;
}

Server Block

Basic server block configuration

Nginx
# Basic server block
server {
    listen 80;
    server_name example.com www.example.com;
    root /var/www/html;
    index index.html index.htm;

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

    location /api {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

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

Common Directives

Common Nginx directives and settings

Nginx
# Common Nginx directives
server {
    # Basic settings
    listen 80;
    server_name example.com;
    root /var/www/html;
    
    # Client settings
    client_max_body_size 10M;
    client_body_buffer_size 128k;
    client_header_buffer_size 1k;
    
    # Timeouts
    client_body_timeout 12;
    client_header_timeout 12;
    keepalive_timeout 15;
    send_timeout 10;
    
    # Buffer settings
    large_client_header_buffers 4 4k;
    client_body_buffer_size 128k;
    
    # File settings
    open_file_cache max=1000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;
}

SSL/TLS Configuration

SSL Configuration

SSL/TLS configuration

Nginx
# SSL configuration
server {
    listen 443 ssl http2;
    server_name example.com;
    
    ssl_certificate /etc/nginx/ssl/example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com.key;
    
    # SSL settings
    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:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    
    # HSTS
    add_header Strict-Transport-Security "max-age=63072000" always;
    
    # OCSP Stapling
    ssl_stapling on;
    ssl_stapling_verify on;
    resolver 8.8.8.8 8.8.4.4 valid=300s;
    resolver_timeout 5s;
}

HTTP to HTTPS Redirect

HTTP to HTTPS redirection

Nginx
# Redirect HTTP to HTTPS
server {
    listen 80;
    server_name example.com;
    return 301 https://$server_name$request_uri;
}

# HTTPS server
server {
    listen 443 ssl http2;
    server_name example.com;
    # ... SSL configuration ...
}

SSL Certificate Renewal

SSL certificate renewal

Nginx
# Certbot renewal
certbot renew --nginx

# Manual renewal
certbot certonly --nginx -d example.com -d www.example.com

# Test renewal
certbot renew --dry-run

# Auto-renewal cron job
0 0 1 * * certbot renew --quiet

Caching and Performance

Proxy Caching

Proxy caching configuration

Nginx
# Proxy cache configuration
http {
    proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;
    
    server {
        location / {
            proxy_cache my_cache;
            proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504;
            proxy_cache_valid 200 60m;
            proxy_cache_valid 404 1m;
            proxy_cache_bypass $http_cache_control;
            add_header X-Cache-Status $upstream_cache_status;
            
            proxy_pass http://backend;
        }
    }
}

FastCGI Caching

FastCGI caching configuration

Nginx
# FastCGI cache configuration
http {
    fastcgi_cache_path /var/cache/nginx/fastcgi_cache levels=1:2 keys_zone=php_cache:10m max_size=10g inactive=60m use_temp_path=off;
    
    server {
        location ~ .php$ {
            fastcgi_cache php_cache;
            fastcgi_cache_valid 200 60m;
            fastcgi_cache_valid 404 1m;
            fastcgi_cache_use_stale error timeout invalid_header http_500;
            fastcgi_cache_bypass $http_cache_control;
            add_header X-FastCGI-Cache $upstream_cache_status;
            
            fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
        }
    }
}

Gzip Compression

Gzip compression configuration

Nginx
# Gzip compression
http {
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_types text/plain text/css text/xml application/json application/javascript application/xml+rss application/atom+xml image/svg+xml;
    gzip_min_length 1000;
    gzip_disable "MSIE [1-6].";
}

Security

Security Headers

Security headers configuration

Nginx
# Security headers
server {
    # Basic security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "no-referrer-when-downgrade" always;
    add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    
    # Remove server version
    server_tokens off;
}

Rate Limiting

Rate limiting configuration

Nginx
# Rate limiting
http {
    # Define rate limit zones
    limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
    limit_conn_zone $binary_remote_addr zone=addr:10m;
    
    server {
        location /login {
            limit_req zone=one burst=5 nodelay;
            limit_conn addr 10;
            limit_rate 100k;
        }
        
        location /api {
            limit_req zone=one burst=10 nodelay;
            limit_conn addr 20;
        }
    }
}

Access Control

Access control configuration

Nginx
# Access control
server {
    # IP-based access control
    allow 192.168.1.0/24;
    deny all;
    
    # Basic authentication
    location /admin {
        auth_basic "Restricted Access";
        auth_basic_user_file /etc/nginx/.htpasswd;
    }
    
    # Deny access to hidden files
    location ~ /. {
        deny all;
        access_log off;
        log_not_found off;
    }
}

Advanced Features

Load Balancing

Load balancing configuration

Nginx
# Load balancing
http {
    upstream backend {
        least_conn;  # Load balancing method
        server backend1.example.com:8080 weight=5;
        server backend2.example.com:8080 weight=5;
        server backend3.example.com:8080 backup;
    }
    
    server {
        location / {
            proxy_pass http://backend;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }
    }
}

WebSocket Support

WebSocket configuration

Nginx
# WebSocket configuration
server {
    location /ws {
        proxy_pass http://websocket_backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        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_read_timeout 300s;
        proxy_send_timeout 300s;
    }
}

URL Rewriting

URL rewriting configuration

Nginx
# URL rewriting
server {
    # Basic rewrite
    rewrite ^/old-path$ /new-path permanent;
    
    # Complex rewrite rules
    location /blog {
        rewrite ^/blog/([0-9]+)/?$ /blog.php?id=$1 last;
        rewrite ^/blog/category/([^/]+)/?$ /blog.php?category=$1 last;
    }
    
    # Conditional rewrite
    if ($http_user_agent ~* (mobile|tablet)) {
        rewrite ^/desktop/(.*)$ /mobile/$1 last;
    }
}

Nginx - Interactive Developer Reference

Hover over code blocks to copy or run in live playground