nginx Episode 1
- Atul
- Technology , Web , Free software , The big o community , Self hosting , Nginx
- May 28, 2025
Table of Contents
nginx Episode 1
π° The Nginx Kingdom Guide: A Web Server’s Epic Adventure
Welcome, brave adventurer, to the mystical realm of Nginx - where web requests are quests, and servers are mighty fortresses! βοΈ
π Chapter 1: The Legend of Nginx
In the ancient kingdom of Web-landia, there lived a powerful wizard named Nginx (pronounced “Engine-X” π§ββοΈ). This wasn’t just any ordinary wizard - he was the Master of Traffic and Guardian of the Gates, capable of handling thousands of simultaneous quests without breaking a sweat!
ποΈ The Architecture of Our Fortress
π° The Nginx Castle
/\ /\
/ \ / \
/____\/____\
| π‘οΈ NGINX π‘οΈ |
| Load Balancer |
|________________|
/ | \
/ | \
π App1 π App2 π App3
:3000 :3001 :3002
πΊοΈ Chapter 2: The Quest Begins - Installation Magic
π§ Ubuntu/Debian Realm
# Update the kingdom's knowledge
sudo apt update
# Summon the Nginx wizard
sudo apt install nginx
# Awaken the sleeping giant
sudo systemctl start nginx
# Bind the wizard to serve forever
sudo systemctl enable nginx
π© CentOS/RHEL Territory
# Install from the royal repositories
sudo yum install nginx
# OR for newer kingdoms
sudo dnf install nginx
# Start the magical service
sudo systemctl start nginx
sudo systemctl enable nginx
π macOS Enchanted Forest
# Using the Homebrew potion
brew install nginx
# Start the local fortress
brew services start nginx
π° Chapter 3: The Sacred Configuration Scrolls
The heart of our Nginx kingdom lies in its configuration files - ancient scrolls that determine how our fortress operates!
π Main Configuration Location
- Ubuntu/Debian:
/etc/nginx/nginx.conf
- CentOS/RHEL:
/etc/nginx/nginx.conf
- macOS:
/opt/homebrew/etc/nginx/nginx.conf
ποΈ The Directory Structure
/etc/nginx/
βββ π nginx.conf (The Master Scroll)
βββ π sites-available/ (Dormant Spells)
βββ π sites-enabled/ (Active Magic)
βββ π conf.d/ (Additional Enchantments)
βββ π snippets/ (Reusable Incantations)
π Chapter 4: The Art of Configuration Spells
β‘ Basic Web Server Spell
# /etc/nginx/sites-available/my-kingdom
server {
listen 80; π§
server_name my-kingdom.com www.my-kingdom.com; π°
root /var/www/my-kingdom; π
index index.html index.htm; π
location / {
try_files $uri $uri/ =404; π
}
# Logging for the royal chronicles
access_log /var/log/nginx/my-kingdom.access.log; π
error_log /var/log/nginx/my-kingdom.error.log; β οΈ
}
π Reverse Proxy Magic (For Your React/Next.js Apps!)
# Perfect for your Next.js applications! βοΈ
server {
listen 80;
server_name my-react-kingdom.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;
}
}
βοΈ Load Balancing Sorcery
# The spell to distribute power across multiple servers
upstream my_app_servers {
server 127.0.0.1:3000 weight=3; πͺ
server 127.0.0.1:3001 weight=2; ποΈ
server 127.0.0.1:3002 weight=1; π€Έ
}
server {
listen 80;
server_name load-balanced-kingdom.com;
location / {
proxy_pass http://my_app_servers; βοΈ
}
}
π‘οΈ Chapter 5: SSL/TLS Protection Enchantments
π Let’s Encrypt Magic (FOSS Way!)
# Install the Certbot wizard (Ubuntu/Debian)
sudo apt install certbot python3-certbot-nginx
# Cast the SSL protection spell
sudo certbot --nginx -d your-kingdom.com -d www.your-kingdom.com
# Auto-renewal incantation
sudo crontab -e
# Add this line for eternal protection:
0 12 * * * /usr/bin/certbot renew --quiet
π SSL Configuration Spell
server {
listen 443 ssl http2; π
server_name secure-kingdom.com;
ssl_certificate /etc/letsencrypt/live/secure-kingdom.com/fullchain.pem; π
ssl_certificate_key /etc/letsencrypt/live/secure-kingdom.com/privkey.pem; ποΈ
# Modern SSL incantations
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers off;
# Security headers enchantments
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;
}
# Redirect HTTP to HTTPS (Force the secure path!)
server {
listen 80;
server_name secure-kingdom.com;
return 301 https://$server_name$request_uri; β©οΈ
}
π― Chapter 6: Performance Optimization Spells
π Caching Magic
# Enable the memory enhancement spells
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_revalidate on;
proxy_cache_min_uses 3;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
proxy_cache_background_update on;
proxy_cache_lock on;
proxy_pass http://localhost:3000;
}
}
}
π¦ Compression Enchantment
# Make everything smaller and faster!
http {
gzip on; ποΈ
gzip_vary on;
gzip_min_length 1024;
gzip_comp_level 6;
gzip_types
text/plain
text/css
text/xml
text/javascript
application/javascript
application/xml+rss
application/json;
}
π§ Chapter 7: Essential Nginx Incantations
πββοΈ Service Management Spells
# Check if the wizard is awake
sudo systemctl status nginx ποΈ
# Wake up the sleeping wizard
sudo systemctl start nginx π
# Put the wizard to sleep
sudo systemctl stop nginx π΄
# Restart the wizard (full reboot)
sudo systemctl restart nginx π
# Reload configuration without downtime
sudo systemctl reload nginx β»οΈ
# Test configuration before applying
sudo nginx -t π§ͺ
π Monitoring & Debugging Spells
# View the royal access logs
sudo tail -f /var/log/nginx/access.log π
# Check for errors in the kingdom
sudo tail -f /var/log/nginx/error.log β οΈ
# See active connections
sudo netstat -tuln | grep :80 π
# Check Nginx processes
ps aux | grep nginx π₯
πΊοΈ Chapter 8: Advanced Quest Configurations
π¨ Static Assets Optimization (Perfect for React builds!)
server {
listen 80;
server_name my-react-app.com;
# Serve React build files
location / {
root /var/www/react-build;
try_files $uri $uri/ /index.html; # SPA routing magic! βοΈ
}
# Cache static assets forever
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2)$ {
root /var/www/react-build;
expires 1y; π
add_header Cache-Control "public, immutable";
}
}
π API Gateway Configuration
# Perfect for your Next.js API routes!
server {
listen 80;
server_name api-gateway.com;
# Route to different API services
location /api/v1/users {
proxy_pass http://localhost:3001/users; π₯
}
location /api/v1/products {
proxy_pass http://localhost:3002/products; ποΈ
}
location /api/v1/orders {
proxy_pass http://localhost:3003/orders; π¦
}
# Default API route
location /api/ {
proxy_pass http://localhost:3000; π―
}
}
π Chapter 9: The Traffic Flow Diagram
graph TB Client[π€ Brave Adventurer<br/>Client Request] DNS[πΊοΈ DNS Lookup<br/>Kingdom Locator] LB[βοΈ Load Balancer<br/>Traffic Distributor] Nginx[π° Nginx Fortress<br/>Reverse Proxy] App1[βοΈ React App<br/>:3000] App2[π’ Node.js API<br/>:3001] App3[π Python Service<br/>:3002] DB[(ποΈ Database<br/>Treasure Vault)] Cache[πΎ Redis Cache<br/>Memory Scroll] Client --> DNS DNS --> LB LB --> Nginx Nginx --> App1 Nginx --> App2 Nginx --> App3 App2 --> DB App2 --> Cache App3 --> DB style Client fill:#e1f5fe style Nginx fill:#f3e5f5 style App1 fill:#e8f5e8 style DB fill:#fff3e0
π‘οΈ Chapter 10: Security Fortress Enchantments
π Security Headers Spell Book
server {
# Content Security Policy
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:;"; π‘οΈ
# Prevent clickjacking
add_header X-Frame-Options "SAMEORIGIN" always; πΌοΈ
# MIME type sniffing protection
add_header X-Content-Type-Options "nosniff" always; π
# XSS protection
add_header X-XSS-Protection "1; mode=block" always; βοΈ
# Referrer policy
add_header Referrer-Policy "strict-origin-when-cross-origin" always; π
}
π« Rate Limiting Magic
# Protect against DDoS attacks
http {
limit_req_zone $binary_remote_addr zone=login:10m rate=1r/s; π‘οΈ
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s; β‘
server {
location /login {
limit_req zone=login burst=3 nodelay;
proxy_pass http://localhost:3000;
}
location /api/ {
limit_req zone=api burst=20 nodelay;
proxy_pass http://localhost:3001;
}
}
}
π Chapter 11: Troubleshooting & Common Quests
π Common Issues & Solutions
π¨ “502 Bad Gateway” Dragon
# Check if your application is running
sudo netstat -tuln | grep :3000
# Verify Nginx can reach your app
curl http://localhost:3000
# Check Nginx error logs
sudo tail -f /var/log/nginx/error.log
π₯ “413 Request Entity Too Large” Giant
# Increase upload size limits
http {
client_max_body_size 100M; π€
}
β‘ SSL Certificate Troubles
# Test SSL configuration
sudo nginx -t
# Renew Let's Encrypt certificates
sudo certbot renew --dry-run
# Check certificate expiration
sudo certbot certificates
π Chapter 12: Victory Celebration - Best Practices
β¨ The Sacred Rules of Nginx Mastery
- π§ͺ Always test configurations:
sudo nginx -t
before applying - π Keep logs organized: Separate logs for different domains
- π Use graceful reloads:
sudo systemctl reload nginx
for config changes - πΎ Implement caching: Speed up your React/Next.js apps
- π Secure everything: SSL, security headers, rate limiting
- π Monitor performance: Regular log analysis and metrics
- π§ Keep it updated: Regular Nginx updates for security
π― Perfect Setup for Your JS/TS/React/Next.js Stack
# The ultimate configuration for modern web apps
server {
listen 443 ssl http2;
server_name your-awesome-app.com;
# SSL configuration (Let's Encrypt)
ssl_certificate /etc/letsencrypt/live/your-awesome-app.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/your-awesome-app.com/privkey.pem;
# Security headers
include /etc/nginx/snippets/security-headers.conf;
# Main application (Next.js)
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;
# Perfect for Next.js hot reload! π₯
}
# API routes
location /api/ {
proxy_pass http://localhost:3001;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
# Static assets with long-term caching
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
access_log off;
}
}
π Epilogue: Your Nginx Kingdom Awaits!
Congratulations, noble web warrior! π You’ve mastered the ancient arts of Nginx configuration. Your fortress now stands ready to:
- β‘ Handle thousands of concurrent adventurers (users)
- π‘οΈ Protect against malicious dragons (attacks)
- π Serve your React/Next.js applications with lightning speed
- π Keep everything secure with SSL encryption
- βοΈ Balance loads like a seasoned juggler
Remember, every great kingdom needs maintenance. Keep your configurations updated, monitor your logs, and may your servers never go down! π°β¨
“With great power comes great responsibility… and awesome web performance!” - The Nginx Wizard π§ββοΈ
π Quick Reference Commands
# Test configuration
sudo nginx -t
# Reload without downtime
sudo systemctl reload nginx
# View active sites
ls -la /etc/nginx/sites-enabled/
# Check syntax and reload
sudo nginx -t && sudo systemctl reload nginx
# Monitor real-time logs
sudo tail -f /var/log/nginx/access.log /var/log/nginx/error.log
Go forth and serve the web, brave administrator! Your Nginx kingdom awaits! π