Caching Static Files in Nginx
How to Speed Up Page Load, Optimize Traffic, and Control Cache
Properly configuring caching and compression for static resources on your web server can significantly speed up page load times and reduce server load. In this article, we’ll cover how to set cache expiration using the Expires directive and enable GZIP compression for static files in Nginx.
Setting the Expires Directive for Static Files
The Expires directive defines how long cached resources are considered fresh. This allows browsers to use local copies of files without sending repeated requests to the server.
Open the Nginx configuration file for your virtual host, usually /etc/nginx/nginx.conf
on Linux. Locate the server {} block that contains the location section for serving static files.
Example configuration for a location block:
location ~* \.(jpg|jpeg|gif|png|svg|js|css|mp3|ogg|mpeg|avi|zip|gz|bz2|rar|swf)$ {
root /var/www/username/data/www/usernamesite.ru;
access_log /var/www/nginx-logs/usernamesite isp;
access_log /var/www/httpd-logs/usernamesite.ru.access.log;
error_page 404 = @fallback;
expires 7d;
}
- expires 7d — tells the browser to cache the resource for 7 days.
- For files that change infrequently, like CSS, JS, or images, you can increase the cache duration to several months or even a year.
Applying the Template to All Virtual Hosts
To automatically apply the Expires directive to static files for all virtual hosts via the control panel, create a file /usr/local/ispmgr/etc/server.templ
with the following content:
location ~* \.(jpg|jpeg|gif|png|svg|js|css|mp3|ogg|mpeg|avi|zip|gz|bz2|rar|swf)$ {
expires 7d;
}
Enabling GZIP Compression for Static Files
GZIP compression reduces the size of text-based files, lowering the amount of data transmitted and speeding up page load times.
Add the following directives to the server {} block of your virtual host:
server {
...
gzip on;
gzip_disable "msie6";
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
}
- gzip on; — enables compression.
- gzip_disable "msie6"; — disables compression for older browsers such as Internet Explorer 6.
- gzip_types — specifies the MIME types that should be compressed.
Note
On a VPS or dedicated server, you have full control over Nginx configuration, including caching and compression. This allows you to optimize site performance and reduce server load.