Containers

Pre-compress static web files using GZip and Brotli automatically

If you’ve worked with the web for any amount of time, you’ll know that compression is one of the very best ways of improving page load times. You might also be annoyed by the fact that you’re wasting CPU cycles on compressing the same files over and over – not to mention the added latency waiting for the compression to complete. The best option is to pre-compress all of your static files as part of the build or deploy process of your web application. For just this requirement, I’ve created a small Node script that’ll recurse through a directory compressing all of the files it locates.

The Code

You can find the Gist here: https://gist.github.com/danclarke/7a5b647d38a63241b71fb3743db15160

Simply update the last line to point to the directory you want to compress. By default, I’ve got the script compressing ‘dist’.

compressDir('dist');

Nginx

Next, you’ll need to configure your web server to use the pre-compressed files instead of compressing them on the fly. For Nginx you’ll need to do the following:

Then add the following lines to your Nginx config for either the http configuration or the location configuration:

  • gzip_static on;
  • brotli_static on;

And that’s it!

Docker

If you want to use Nginx in a Docker container with Brotli, you can use this very cool Github project: https://github.com/fholzer/docker-nginx-brotli. Then in the Dockerfile for your website, ensure you use your custom Nginx image instead of the official one.

My configuration for Nginx looks like the following:

server {
    listen       80;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        gzip_static   on;
        brotli_static on;
    }
}
Posted by Dan in Programming, 0 comments