Blogpost

Published: 2020-06-20

Nginx: use "cached compression"

How to enable Nginx to use a cached compressed version of a file, if it exists, instead of calculating the compressed version on each request. I will show you how you can prepare the compressed files on linux.

"The ngx_http_gzip_static_module module allows sending precompressed files with the “.gz” filename extension instead of regular files." taken from the docs. This means, if you have a file "index.html", Nginx will check if there exists a file "index.html.gz" within the same folder.

Start

Zip

Table of contents

Check if the http_gzip_static_module is included

sudo nginx -V |& grep -o "http_gzip_static_module" if this returns you "http_gzip_static_module" then you have the necessary module already installed. If it does not you should have a look here on how to include not default Nginx modules.

Nginx configuration

Add the following line to your nginx site configuration:

  • gzip_static on;

Create the compressed files

Within the folder you want to provide zipped versions of your files issue: gzip -kNr *. "-k" will keep the input files. "-N" will restore the original name and timestamp. "-r" will execute the command recursively in subfolders. If you want to only compress a certain type of file use find /path/to/folder \( -name '*.css' -o -name '*.html' -o -name '*.js' \) -exec gzip -kNv {} \; for ".html" and ".css" files for example.

List of commands

  • details about nginx version and configure arguments sudo nginx -V
  • gzipping files of certain type within current folder find . \( -name '*.css' -o -name '*.html' -o -name '*.js' \) -exec gzip -kNvf {} \;
    • "-N" .gz-files keep name and timestamp of original
    • "-f" overwrites existing .gz-files
    • "-v" verboes
    • "-f" force, add it to overwrite existing zipped files

Links

Sources

Tags

#nginx #linux #tutorial