Nginx Configuration Cheatsheet — Server Blocks, Proxy, SSL

Nginx config examples: server blocks, reverse proxy, SSL/TLS, caching, redirects, load balancing, security headers.

Basic Server Block

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

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

Reverse Proxy

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

    location / {
        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_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_cache_bypass $http_upgrade;
    }
}

SSL/TLS (Let's Encrypt)

server {
    listen 443 ssl http2;
    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;

    # ... rest of config
}

# HTTP -> HTTPS redirect
server {
    listen 80;
    server_name example.com;
    return 301 https://$server_name$request_uri;
}

Useful Locations

# Static files with caching
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
    expires 30d;
    add_header Cache-Control "public, immutable";
}

# API proxy with CORS
location /api/ {
    add_header Access-Control-Allow-Origin *;
    proxy_pass http://localhost:8080/;
}

# Deny hidden files
location ~ /\. {
    deny all;
}

Common Commands

nginx -t                  # Test config
nginx -s reload           # Reload config
nginx -s stop             # Stop
systemctl restart nginx   # Restart service

Need These Tools as an API?

TextForge API offers 20+ developer toolkit endpoints. Free tier: 50 requests/day.

Try TextForge API Free →

Related Tools