Nginx: The Web Server You'll Always Need
Nginx sits in front of your application. It handles SSL termination, serves static files, load balances, and reverse proxies to your app servers. Even if you use a PaaS, understanding Nginx helps debug production issues.
Basic Reverse Proxy
server {
listen 80;
server_name 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;
}
}SSL with 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;
# Modern SSL settings
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto https;
}
}
# Redirect HTTP to HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}Serve Static Files
server {
listen 80;
root /var/www/html;
# Static files with long cache
location /static/ {
expires 1y;
add_header Cache-Control "public, immutable";
}
# Try file, then directory, then fallback to app
location / {
try_files $uri $uri/ @app;
}
location @app {
proxy_pass http://localhost:3000;
}
}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 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;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Content-Security-Policy "default-src 'self'" 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;
}
}Common Commands
nginx -t # test config syntax
systemctl reload nginx # apply changes without downtime
systemctl restart nginx # full restart
nginx -T # dump full config
tail -f /var/log/nginx/error.log # watch errorsReference: Linux Cheatsheet — server commands for managing Nginx.