Nginx Cheat Sheet: Configuration, Reverse Proxy, SSL, and More

4 min read
Intermediate Nginx Web Server Reverse Proxy Cheat Sheet

Prerequisites

  • Nginx installed (apt install nginx)
  • Basic understanding of HTTP and DNS

Quick Answer: Config file: /etc/nginx/sites-available/mysite. Test config: nginx -t. Reload: systemctl reload nginx. Reverse proxy: proxy_pass http://localhost:3000;. SSL: use certbot --nginx -d example.com.

Install and Control

# Install
apt update && apt install nginx -y

# Control
systemctl start nginx
systemctl stop nginx
systemctl restart nginx        # Full restart (drops connections)
systemctl reload nginx         # Graceful reload (no downtime)
systemctl status nginx

# Test configuration (always do this before reload)
nginx -t

# View version and compiled modules
nginx -V

File Locations

File Purpose
/etc/nginx/nginx.conf Main config
/etc/nginx/sites-available/ Site configs (available)
/etc/nginx/sites-enabled/ Site configs (active — symlinks)
/etc/nginx/snippets/ Reusable config fragments
/var/log/nginx/access.log Access log
/var/log/nginx/error.log Error log
/var/www/html/ Default web root
# Enable a site
ln -s /etc/nginx/sites-available/mysite /etc/nginx/sites-enabled/
# Disable a site
rm /etc/nginx/sites-enabled/mysite
# Remove default site
rm /etc/nginx/sites-enabled/default

Basic Server Block

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

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

Reverse Proxy

Basic Proxy

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

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

WebSocket Proxy

location /ws {
    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_read_timeout 86400;
}

Proxy with Timeouts

location / {
    proxy_pass http://localhost:8080;
    proxy_connect_timeout 60s;
    proxy_send_timeout 60s;
    proxy_read_timeout 60s;
    proxy_buffering off;
}

SSL/TLS

Certbot (Let's Encrypt — Easiest)

apt install certbot python3-certbot-nginx -y
certbot --nginx -d example.com -d www.example.com
# Auto-renewal is set up automatically
certbot renew --dry-run    # Test renewal

Manual SSL Config

server {
    listen 443 ssl;
    http2 on;
    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_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    root /var/www/example;
}

HTTP to HTTPS Redirect

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

Redirects

# Permanent redirect (301)
return 301 https://newdomain.com$request_uri;

# Temporary redirect (302)
return 302 /maintenance.html;

# Redirect specific path
location /old-page {
    return 301 /new-page;
}

# Redirect non-www to www
server {
    listen 80;
    server_name example.com;
    return 301 https://www.example.com$request_uri;
}

# Redirect www to non-www
server {
    listen 80;
    server_name www.example.com;
    return 301 https://example.com$request_uri;
}

# Redirect with regex
rewrite ^/blog/(.*)$ /articles/$1 permanent;

Load Balancing

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

# Methods:
# upstream backend { }                    # Round robin (default)
# upstream backend { least_conn; }        # Least connections
# upstream backend { ip_hash; }           # Sticky sessions
# upstream backend { server x weight=3; } # Weighted

server {
    listen 80;
    location / {
        proxy_pass http://backend;
    }
}

Caching

Static File Caching

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

Proxy Cache

proxy_cache_path /tmp/nginx_cache levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m;

server {
    location / {
        proxy_pass http://localhost:3000;
        proxy_cache my_cache;
        proxy_cache_valid 200 60m;
        proxy_cache_valid 404 1m;
        add_header X-Cache-Status $upstream_cache_status;
    }
}

Gzip Compression

gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml text/javascript image/svg+xml;

Security

Security Headers

add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "0" always;    # Disabled — use Content-Security-Policy instead
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

Rate Limiting

# Define rate limit zone (10 requests/second per IP)
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;

server {
    location /api/ {
        limit_req zone=api burst=20 nodelay;
        proxy_pass http://localhost:3000;
    }
}

Block IPs

# Block specific IPs
deny 1.2.3.4;
deny 10.0.0.0/8;
allow all;

# Allow only specific IPs
allow 10.0.0.5;
allow 192.168.1.0/24;
deny all;

Block User Agents (Bots)

if ($http_user_agent ~* (bot|crawl|spider|scraper)) {
    return 403;
}

Password Protection

apt install apache2-utils
htpasswd -c /etc/nginx/.htpasswd admin
location /admin {
    auth_basic "Restricted";
    auth_basic_user_file /etc/nginx/.htpasswd;
}

Custom Error Pages

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

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

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';

# Per-site log
access_log /var/log/nginx/mysite-access.log main;
error_log /var/log/nginx/mysite-error.log warn;

# Disable logging for static files
location ~* \.(jpg|css|js|ico)$ {
    access_log off;
}

# Disable logging entirely
access_log off;

Performance Tuning

# In nginx.conf (main context)
worker_processes auto;          # Match CPU cores

# In events context
events {
    worker_connections 1024;    # Per worker
}

# In http context
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
client_max_body_size 100m;      # Max upload size

# Buffer sizes
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;

Common Patterns

SPA (Single Page App)

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

CORS Headers

location /api/ {
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
    add_header Access-Control-Allow-Headers "Authorization, Content-Type";

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

Serve Static + Proxy API

server {
    listen 80;

    # Static files
    location / {
        root /var/www/frontend;
        try_files $uri $uri/ /index.html;
    }

    # API proxy
    location /api/ {
        proxy_pass http://localhost:3000/;
    }
}

Debugging

# Test config
nginx -t

# Check error log
tail -f /var/log/nginx/error.log

# Check which processes are running
ps aux | grep nginx

# Check what's listening on port 80
ss -tlnp | grep :80

# Dump full active config
nginx -T

See Also