nginx: 10 Configuration Hacks¶
nginx is the most popular reverse proxy. Here are 10 configuration hacks for performance and security.
1. Gzip¶
gzip on; gzip_vary on; gzip_min_length 1024; gzip_types text/plain text/css application/json application/javascript;
2. Security Headers¶
add_header X-Frame-Options “SAMEORIGIN” always; add_header X-Content-Type-Options “nosniff” always; add_header Strict-Transport-Security “max-age=31536000” always;
3. Rate Limiting¶
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s; location /api/ { limit_req zone=api burst=20 nodelay; }
4. Static File Caching¶
location ~* .(jpg|png|css|js|woff2)$ { expires 1y; add_header Cache-Control “public, immutable”; }
5. WebSocket Proxy¶
location /ws/ { proxy_pass http://backend:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection “upgrade”; }
6. Load Balancing¶
upstream backend { least_conn; server 10.0.0.1:3000; server 10.0.0.2:3000; }
7. Custom Error Pages¶
error_page 404 /404.html; error_page 500 502 503 504 /50x.html;
8. Bot Blocking¶
if ($http_user_agent ~* (SemrushBot|AhrefsBot)) { return 403; }
9. SSL Optimization¶
ssl_protocols TLSv1.2 TLSv1.3; ssl_session_cache shared:SSL:10m; ssl_stapling on;
10. Test Configuration¶
nginx -t nginx -s reload
Tip¶
Always run nginx -t before reloading. A single syntax error can bring down the server.