MeshWorld India LogoMeshWorld.

Nginx Cheat Sheet: Config, Routing, SSL & Performance (2026)

Vishnu
By Vishnu
|Updated: Jul 30, 2026
Nginx Cheat Sheet: Config, Routing, SSL & Performance (2026)

Nginx is the world’s leading high-performance web server, reverse proxy, load balancer, and HTTP cache. Operating Nginx in modern cloud production environments requires mastering server block directives, location matching rules, reverse proxy headers (X-Forwarded-For), TLS security hardening, rate limiting, and HTTP/3 QUIC configurations.

Key Takeaways

  • Always test Nginx configuration syntax using `sudo nginx -t` before reloading systemd services.
  • Understand location matching priority (`=` exact > `^~` non-regex > `~*` regex > `/` catch-all) to avoid routing bugs.
  • Configure reverse proxying using `proxy_pass http://127.0.0.1:3000;` with proper WebSocket and header overrides.
  • Automate free SSL/TLS certificate creation and renewal via Certbot (`sudo certbot --nginx`).
  • Implement rate limiting using `limit_req_zone` and `limit_req` to protect backend services from DDoS traffic.

How do you control Nginx process operations and test configuration syntax?

Managing Nginx requires testing configuration files for syntax errors using nginx -t before performing zero-downtime service reloads. Testing configuration files ensures invalid directive syntax or missing SSL certificate files never crash production services.

Common CLI Commands

CommandAction
nginx -tTest configuration syntax (always run before reloading)
nginx -TTest configuration syntax and dump full compiled configuration
nginx -s reloadReload configuration without dropping active client connections
nginx -s stopFast shutdown (terminates active connections immediately)
nginx -s quitGraceful shutdown (waits for active requests to finish)
systemctl reload nginxReload Nginx configuration via systemd
systemctl restart nginxFull restart of Nginx daemon via systemd
nginx -vDisplay Nginx version
nginx -VDisplay Nginx version along with compiler options and enabled modules

What are the quick reference rules for Nginx server blocks and location matching?

Nginx uses server blocks to define virtual hosts and location blocks to route incoming request URIs. Mastering location match evaluation priority prevents routing bugs when serving static assets or proxying API routes.

Server Blocks & Routing

DirectiveAction
server { ... }Define a virtual host
listen 80;Listen on IPv4 port 80 (HTTP)
listen [::]:80;Listen on IPv6 port 80
listen 443 ssl;Listen on port 443 with TLS enabled
http2 on;Enable HTTP/2 protocol support
server_name example.com www.example.com;Match request Host header
server_name *.example.com;Wildcard domain matching
root /var/www/html;Base directory for static file lookup
index index.html index.htm;Default file to serve for directory requests
try_files $uri $uri/ /index.html;SPA routing (fallback to index.html)

Location Matching Priority

ModifierPriorityDescription
location = /path1 (Highest)Exact string match
location ^~ /prefix/2Prefix match; if matched, skip regex evaluation
location ~ \.php$3Case-sensitive regular expression match
location ~* \.(jpg|png)$3Case-insensitive regular expression match
location /4 (Lowest)Default prefix match (catch-all)

Reverse Proxy (proxy_pass)

DirectiveAction
proxy_pass http://127.0.0.1:3000;Forward request to backend server
proxy_set_header Host $host;Preserve original Host header
proxy_set_header X-Real-IP $remote_addr;Pass real client IP address
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;Pass client and upstream proxy chain IPs
proxy_set_header X-Forwarded-Proto $scheme;Pass protocol (http or https)
proxy_http_version 1.1;Required for keepalive and WebSockets
proxy_set_header Upgrade $http_upgrade;WebSocket connection upgrade header
proxy_set_header Connection "upgrade";WebSocket connection upgrade header
proxy_read_timeout 60s;Max time between read operations from backend

How do you configure SSL/TLS certificates, security headers, and redirects?

Securing Nginx requires enforcing TLS 1.2/1.3 encryption protocols, strong cipher suites, security headers, and automatic HTTP-to-HTTPS redirects. Enabling HSTS and OCSP stapling optimizes TLS handshake performance while protecting users against protocol downgrade attacks.

SSL / TLS Directives

DirectiveAction
ssl_certificate /path/fullchain.pem;Path to certificate chain file
ssl_certificate_key /path/privkey.pem;Path to private key file
ssl_protocols TLSv1.2 TLSv1.3;Allow only secure TLS 1.2 and TLS 1.3 protocols
ssl_ciphers HIGH:!aNULL:!MD5;Set allowed secure cipher suites
ssl_prefer_server_ciphers on;Prefer server cipher preference order
ssl_session_cache shared:SSL:10m;Shared SSL session cache (10MB stores ~40k sessions)
ssl_session_timeout 1d;SSL session reuse window duration
ssl_stapling on;Enable OCSP stapling for faster TLS handshakes
ssl_stapling_verify on;Verify server OCSP stapling responses

Security Headers

DirectiveAction
add_header X-Frame-Options "DENY";Prevent clickjacking by blocking iframe embedding
add_header X-Content-Type-Options "nosniff";Prevent MIME-type sniffing
add_header X-XSS-Protection "1; mode=block";Enable cross-site scripting filtering (legacy)
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;Enforce HSTS for 1 year
add_header Referrer-Policy "strict-origin-when-cross-origin";Restrict referrer header leakage
add_header Content-Security-Policy "default-src 'self'";Define Content Security Policy
add_header ... always;Apply header even on error responses

Redirects

DirectiveAction
return 301 https://$host$request_uri;Permanent redirect (HTTP → HTTPS)
return 302 /new-path;Temporary redirect
rewrite ^/old$ /new permanent;Regex-based permanent 301 redirect
rewrite ^/old(.*)$ /new$1 permanent;Redirect with path parameter preservation

How do you configure static file caching, gzip compression, rate limiting, and upstreams?

Performance optimization in Nginx involves static file descriptor caching, response stream compression, upstream load balancing, and client rate limiting. Utilizing gzip and immutable Cache-Control headers significantly speeds up web application rendering times for end users.

Static File Serving & Caching

DirectiveAction
expires 1y;Set Cache-Control and Expires headers to 1 year
expires -1;Disable client caching for location
add_header Cache-Control "public, immutable";Mark hashed static assets as immutable
etag on;Enable ETag generation
open_file_cache max=1000 inactive=20s;Cache open file descriptors in memory
gzip on;Enable gzip response compression
gzip_types text/plain text/css application/json application/javascript;Set MIME types to compress
gzip_min_length 1000;Do not compress files smaller than 1KB
gzip_comp_level 6;Compression level 1–9 (level 6 provides optimal CPU balance)

Rate Limiting & Connections

DirectiveAction
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;Define rate limit zone (in http block)
limit_req zone=api burst=20 nodelay;Apply rate limit with burst buffer in location block
limit_req_status 429;Return 429 Too Many Requests status code
limit_conn_zone $binary_remote_addr zone=conn:10m;Define connection limit zone
limit_conn conn 10;Restrict client IP to 10 max concurrent connections

Upstream (Load Balancing)

DirectiveAction
upstream backend { server 127.0.0.1:3000; server 127.0.0.1:3001; }Define upstream backend cluster
server 127.0.0.1:3001 weight=2;Weighted load balancing distribution
server 127.0.0.1:3002 backup;Designate failover backup server
least_conn;Route requests to server with fewest active connections
ip_hash;Enable sticky sessions by client IP address
keepalive 32;Maintain persistent open connections to upstream servers

What is a complete, production-ready HTTPS Nginx server configuration template?

This production-ready HTTPS configuration includes HTTP-to-HTTPS redirection, TLS 1.2/1.3 security hardening, gzip compression, proxy headers, and static asset caching. Deploying this template ensures robust security and high performance out-of-the-box.

nginx
# Redirect all HTTP traffic to HTTPS
server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;
    return 301 https://$host$request_uri;
}

# Main HTTPS server
server {
    listen 443 ssl;
    listen [::]:443 ssl;
    http2 on;
    server_name example.com www.example.com;

    # SSL Certificates
    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_session_cache   shared:SSL:10m;
    ssl_session_timeout 1d;
    ssl_stapling        on;
    ssl_stapling_verify on;

    # Security Headers
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header X-Frame-Options "DENY" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    server_tokens off;

    # Gzip Compression
    gzip on;
    gzip_types text/plain text/css application/json application/javascript application/xml;
    gzip_min_length 1000;

    # Reverse Proxy to Node.js / Python application
    location / {
        proxy_pass         http://127.0.0.1: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_read_timeout 60s;
    }

    # Static assets with 1-year immutable cache
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    # Block access to hidden dotfiles (.env, .git)
    location ~ /\. {
        deny all;
    }
}

Frequently Asked Questions

How do I fix the “413 Request Entity Too Large” error in Nginx?

Add client_max_body_size 100M; inside your http, server, or location block in /etc/nginx/nginx.conf and run sudo systemctl reload nginx.

What is the difference between proxy_pass http://127.0.0.1:3000; and proxy_pass http://127.0.0.1:3000/;?

Including a trailing slash (/) in proxy_pass strips the matching location prefix before forwarding the URL path to the backend, whereas omitting the trailing slash passes the original URI path intact.

How do I configure Let’s Encrypt SSL certificates automatically?

Install Certbot (sudo apt install certbot python3-certbot-nginx) and run sudo certbot --nginx -d example.com -d www.example.com. Certbot automatically edits your server block and configures SSL directives.


Share_This Twitter / X
Vishnu
Written By

Vishnu

Founder & Principal Architect at MeshWorld. Senior engineer and instructor specializing in AI agent systems, scalable web architecture, and modern development workflows.

Enjoyed this article?

Support MeshWorld and help us create more technical content