Caching and compressing static files in Nginx
How to speed up your website and reduce server load.
Properly configuring caching and compression for static files (images, CSS, JavaScript, fonts, etc.) is one of the most effective ways to improve website loading speed, reduce bandwidth usage, and lower the overall load on your server.
In this guide, we’ll cover two essential Nginx features:
- The
expiresdirective for browser caching control - GZIP compression for text-based files
1. Setting up browser caching with expires
The expires directive tells the browser how long it can store a file in its local cache before checking the server again.
Open your site’s Nginx configuration file (usually located at /etc/nginx/conf.d/vhost.conf or similar) and add the following location block for static assets:
location ~* \.(jpg|jpeg|png|gif|svg|webp|ico|css|js|woff|woff2|ttf|eot|mp4|webm|ogg|mp3|pdf|zip)$ {
expires 30d; # Cache for 30 days
add_header Cache-Control "public";
access_log off; # Disable logging for static files to save resources
}
Recommended expires values:
- Images, fonts, and icons:
30dor1y - CSS and JavaScript:
7d—30d(use shorter periods for frequently updated files) - Rarely changing files:
1y
2. Enabling GZIP compression
GZIP compression can dramatically reduce the size of text-based files (HTML, CSS, JS, SVG, etc.), resulting in faster page loads.
Add the following configuration inside your server {} block:
server {
...
gzip on;
gzip_disable "msie6";
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6; # Compression level (1-9)
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_min_length 256;
gzip_types
text/plain
text/css
text/xml
text/javascript
application/javascript
application/json
application/xml
application/rss+xml
image/svg+xml;
}
Our products and services
3. Applying settings to all sites (template)
To automatically apply these optimizations to all virtual hosts, create a template file:
sudo nano /usr/local/ispmgr/etc/server.templ
Add the following:
location ~* \.(jpg|jpeg|png|gif|svg|webp|ico|css|js|woff|woff2|ttf|eot)$ {
expires 30d;
add_header Cache-Control "public";
access_log off;
}
After saving, restart Nginx:
sudo systemctl restart nginx
Useful tips
- Always test your configuration after changes:
sudo nginx -t - Combine
expireswith theCache-Control: publicheader for best performance. - Avoid setting very long cache periods (e.g., more than 1 year) on files that change frequently, such as CSS or JavaScript — otherwise, users may see outdated versions for a long time.
- On VPS or dedicated servers, you can take optimization even further with FastCGI cache, proxy_cache, or advanced browser caching rules.
Help
If you have any questions or need assistance, please contact us through the ticket system — we're always here to help!