Optimizing Nginx Performance: Gzip Compression, Cache Headers, HTTP/2, Logging, and Bandwidth Limiting
This article explains practical Nginx configuration tweaks—including enabling gzip compression, setting cache headers, activating HTTP/2, optimizing logging, and limiting bandwidth—to reduce bandwidth usage and server load, illustrated with code examples and performance impact calculations for typical web traffic.
The core of this guide is to improve website performance by modifying Nginx configuration files. It begins with a brief motivation: during the COVID‑19 pandemic, internet traffic surged, making server optimization essential to reduce bandwidth and load.
1. Enable Gzip Compression – Gzip can dramatically shrink HTML, CSS, and JavaScript payloads. By adding the following directives to nginx.conf , compressed responses drop from 1.15 MB to about 260 KB, saving roughly 80% of transferred data.
gzip on;
gzip_types application/xml application/json text/css text/javascript application/javascript;
gzip_vary on;
gzip_comp_level 6;
gzip_min_length 500;2. Set Cache Headers – Configuring expires and Cache‑Control for static assets (fonts, images, etc.) lets browsers keep copies locally, cutting unnecessary HTTP requests.
location ~* \.(?:jpg|jpeg|gif|png|ico|woff2)$ {
expires 1M;
add_header Cache-Control "public";
}3. Enable HTTP/2 – HTTP/2 reduces the number of TCP connections and improves network utilization. For Nginx 1.9.5+ the protocol is enabled by adding http2 to the listen directive, typically together with TLS.
listen 443 ssl http2;4. Optimize Logging – Reducing log volume saves CPU, I/O, and disk space. Three approaches are shown: (a) disable logging for static resources, (b) conditionally log only non‑2xx/3xx responses, and (c) buffer log writes to reduce I/O.
location ~* \.(?:jpg|jpeg|gif|png|ico|woff2|js|css)$ {
access_log off;
}
map $status $loggable {
~^[23] 0;
default 1;
}
access_log /var/log/nginx/access.log combined if=$loggable;
access_log /var/log/nginx/access.log combined buffer=512k flush=1m;5. Limit Bandwidth – Using limit_rate (and optionally limit_rate_after ) throttles download speeds for large files or specific URLs, preserving bandwidth for critical site components.
location /download/ {
limit_rate 50k;
}
location / {
limit_rate_after 500k;
limit_rate 50k;
}These five techniques together can noticeably improve site responsiveness and reduce network load, especially when applied across many servers worldwide.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.