Nginx
Nginx cheat sheet for reverse proxy, load balancing, SSL/TLS, server blocks, caching, and performance tuning with config examples.
8 min read
nginxweb-serverreverse-proxyload-balancercachesslhttpperformance
Loading your progress
Installation & Basic Commands
Installing and managing Nginx
Installing Nginx on different platforms
bash
# Ubuntu/Debian
sudo apt update
sudo apt install nginx
# CentOS/RHEL/Fedora
sudo yum install nginx
# macOS with Homebrew
brew install nginx
# Check version
nginx -v🚀 Lightweight and high-performance web server
📦 Available in most package managers
🔧 Modular architecture with dynamic modules
⚡ Default config at /etc/nginx/nginx.conf
Essential Nginx management commands
bash
# Start/Stop/Restart
sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx
sudo systemctl reload nginx
# Test configuration
sudo nginx -t
# Show current config
sudo nginx -T✅ Always test config before reload with nginx -t
🔄 Reload applies changes without dropping connections
📁 Config files in /etc/nginx/ directory
📊 Logs in /var/log/nginx/ by default
Server Blocks & Virtual Hosts
Configuring server blocks for multiple sites
Setting up a basic server block
nginx
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}🌐 Server blocks host multiple sites on one server
📝 Each block needs unique server_name
🔗 Symlink from sites-available to sites-enabled
⚡ try_files directive for efficient file serving
Configuring HTTPS with SSL certificates
nginx
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
# Redirect HTTP to HTTPS
location / {
root /var/www/example.com;
}
}🔒 Always use HTTPS in production
📜 Let's Encrypt for free SSL certificates
⚡ HTTP/2 for better performance
🔐 HSTS header for forcing HTTPS
Reverse Proxy
Configuring Nginx as a reverse proxy
Proxying requests to backend servers
nginx
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_cache_bypass $http_upgrade;
}
}🔄 Forwards requests to backend servers
📡 Preserves client IP with X-Real-IP header
🔌 WebSocket support with connection upgrade
⚡ Can cache responses for better performance
Distributing traffic across multiple servers
nginx
upstream backend {
server 10.0.0.1:8080;
server 10.0.0.2:8080;
server 10.0.0.3:8080;
}
server {
location / {
proxy_pass http://backend;
}
}⚖️ Distributes load across multiple servers
🔄 Multiple load balancing algorithms available
💔 Automatic failover with health checks
🎯 Session persistence with ip_hash
Location Blocks & Rewrites
URL matching and request routing
Different types of location matching
nginx
# Exact match
location = /exact {
# Only matches /exact
}
# Prefix match
location /prefix {
# Matches /prefix, /prefix/path, etc.
}
# Regex match
location ~ \.php$ {
# Case-sensitive regex
}
# Regex case-insensitive
location ~* \.(jpg|jpeg|png)$ {
# Case-insensitive regex
}🎯 Exact match (=) has highest priority
📝 Regex locations are evaluated in order
🔍 Use ^~ to prevent regex matching
⚡ Order matters for regex locations
Rewriting and redirecting URLs
nginx
# Simple redirect
location /old {
return 301 /new;
}
# Rewrite rule
location /api {
rewrite ^/api/(.*) /$1 break;
proxy_pass http://backend;
}
# Conditional rewrite
if ($request_uri ~* "/old/(.*)") {
return 301 /new/$1;
}🔄 rewrite changes URI internally
↪️ return sends redirect to client
🏁 break stops processing, last continues
🎯 Use try_files instead of if when possible
Caching & Performance
Optimizing Nginx for better performance
Setting up various caching strategies
nginx
# Browser caching for static files
location ~* \.(jpg|jpeg|png|css|js)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}
# Proxy cache
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=1g;
server {
location / {
proxy_cache my_cache;
proxy_cache_valid 200 1h;
proxy_pass http://backend;
}
}💾 Multiple cache zones for different content
⚡ Microcaching for dynamic content
🔄 stale-while-revalidate for better UX
📊 X-Cache-Status header for debugging
Optimizing Nginx for high performance
nginx
# Worker processes
worker_processes auto;
worker_rlimit_nofile 65535;
events {
worker_connections 4096;
use epoll;
multi_accept on;
}
http {
# Enable compression
gzip on;
gzip_types text/plain text/css application/json application/javascript;
# Keep-alive
keepalive_timeout 65;
keepalive_requests 100;
}⚙️ Tune worker_processes and worker_connections
🗜️ Enable gzip/brotli compression
📈 Use sendfile for static files
🚦 Implement rate limiting for protection
Security & Access Control
Securing your Nginx server
Essential security configurations
nginx
# Hide Nginx version
server_tokens off;
# Security headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
# Rate limiting
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
# IP restrictions
location /admin {
allow 192.168.1.0/24;
deny all;
}🔒 Always hide server version information
🛡️ Implement security headers
⚠️ Use rate limiting to prevent abuse
🔐 Restrict access to sensitive areas