Nginx's default configuration works fine out of the box, but a few targeted tuning changes can meaningfully improve throughput and response times under real production traffic.
Prerequisites
- Nginx installed and running
- Root or sudo access
Tuning Worker Processes
sudo nano /etc/nginx/nginx.conf
worker_processes auto;
worker_connections 1024;
auto matches the worker count to available CPU cores. worker_connections sets the maximum simultaneous connections per worker.
Enabling Gzip Compression
gzip on;
gzip_vary on;
gzip_min_length 256;
gzip_comp_level 5;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
Compression reduces transferred bytes for text-based assets significantly, at a modest CPU cost.
Enabling Static File Caching Headers
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}
Enabling Nginx's Built-in Proxy Cache (For Reverse Proxy Setups)
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=app_cache:10m max_size=1g inactive=60m;
server {
location / {
proxy_cache app_cache;
proxy_cache_valid 200 10m;
proxy_pass http://127.0.0.1:3000;
}
}
Tuning Buffer Sizes
client_body_buffer_size 16k;
client_max_body_size 20m;
client_header_buffer_size 1k;
Increase client_max_body_size if your app needs to accept larger uploads — otherwise Nginx rejects them with a 413 error.
Enabling HTTP Keepalive
keepalive_timeout 65;
keepalive_requests 100;
Applying Changes
sudo nginx -t && sudo systemctl reload nginx
Measuring the Impact
curl -w "@-" -o /dev/null -s https://yourdomain.com <<'EOF'
time_total: %{time_total}s
EOF
For heavier load testing, tools like ab (Apache Bench) or wrk can simulate concurrent requests to compare before/after tuning.
Common Errors
413 Request Entity Too Large — increase client_max_body_size.
504 Gateway Timeout under load — tune proxy_read_timeout and check backend response times directly, not just Nginx settings.
Best Practices
- Change one setting at a time and measure the impact
- Enable gzip for text assets; skip it for already-compressed formats like JPEG/MP4
- Use proxy caching carefully — make sure dynamic/personalized content isn't cached incorrectly
FAQ
Will these changes work on a small VPS?
Yes — most of these settings reduce resource usage rather than increase it (e.g. gzip trades a small amount of CPU for significantly less bandwidth and faster page loads).
Related Articles
- How to Install Nginx on Ubuntu & Debian
- Nginx as a Reverse Proxy for Node.js/Docker Apps
- How to Set Up Basic Load Balancing with Nginx
