gzip_static
Enables NGINX to serve pre-compressed gzip files directly if they exist on the disk.
Description
The gzip_static directive allows NGINX to serve pre-compressed files with the .gz extension rather than compressing files on-the-fly. When enabled, if a request is made for a compressed resource, NGINX will first check for the existence of a corresponding .gz file in the specified location. If it finds one, it serves that file directly, bypassing the gzip module’s runtime compression. This pre-compressed file serves as a way to improve performance, especially during peak traffic times, as it reduces CPU overhead associated with dynamic gzip compression.
The directive accepts a single argument, which can either be on or off, indicating whether to activate or deactivate the feature. When set to on, NGINX checks for the presence of gzip-compressed versions of files (usually suffixed with .gz) during request handling. If no such file is available, NGINX will fall back to serving the regular file (if it exists) or return an error if neither file is found. This behavior enhances the efficiency of resource delivery, especially for text-based content such as HTML, CSS, or JavaScript, where gzip compression typically offers significant size reductions.
It's worth noting that for gzip_static to work efficiently, it is often combined with the gzip directive configured to ensure that compression is applied to files where necessary during the build or deployment stage. Additionally, care must be taken to manage cache headers appropriately to prevent stale data from being served when static files are updated.
Config Example
http {
gzip_static on;
server {
location / {
root /var/www/html;
}
}
}Ensure that the .gz files are correctly generated and placed in the expected directory; otherwise, requests will fail to return the compressed version.
Using gzip_static does not automatically compress files; both the original and .gz files must exist for the feature to function properly.
If gzip_static is enabled without the corresponding gzip directive for live compression, users may miss out on benefits for files that are not pre-compressed.