Our Life TogetherThoughtsAdding Brotli to an Already-built NGINX Instance  —  { code }

I have an already-running instance of NGINX, and I wanted to add Brotli compression. But I did not want to recompile a custom web server from source and replace my repo-installed version. Solution? Create a dynamic Brotli module for NGINX.

I’ve collected steps across the web and summarized them here in this bash script so the installation may be automated. Feel free to execute the codes step-by-step. It will help you troubleshoot any peculiarities on your system.

I was running vanilla NGINX and these two modules were created by the script above: ngx_http_brotli_static_module.so and ngx_http_brotli_filter_module.so. If you are on the latest stable version of NGINX, you may download those files and place them in your NGINX modules folder. Mine was at /usr/share/nginx/modules/.

Activating the modules via NGINX configs

Now that we have the modules, there are two configuration steps needed to activate Brotli compression. First, load the modules in NGINX’s main configuration file (mine was at /etc/nginx/nginx.conf). Outside any block { ... }, on the top-most section of the file, add these lines:


load_module modules/ngx_http_brotli_filter_module.so;
load_module modules/ngx_http_brotli_static_module.so;

Second, activate Brotli (and set its configuration directives, aka settings) either in the http block of /etc/nginx/nginx.conf, or the server block of your domain configs (e.g. /etc/nginx/sites-enabled/). As for me, I placed these directives in the /etc/nginx/snippets/ folder and called them via include in my domain configs.

Google PageSpeed

Another project that aims to speed things up on the web is Google’s best-practices optimization called PageSpeed. I also made a Bash script to automate installation of PageSpeed on a running NGINX server. If you’re interested, check out this post: Adding PageSpeed to an Already-running NGINX Instance.

Updating NGINX

One potential problem I can foresee is when NGINX automatically updates through a package manager. As you can see, dynamic modules are version-specific. NGINX is set not to load modules that were built for a different version. I’m still working on a process to hook this script during apt automatic upgrades. For now, we can hold the automatic upgrade of NGINX packages by using this command:


sudo apt-mark hold nginx nginx-extras

When it’s time for an upgrade, simply unhold those packages, and run the Bash script above. If all is well in your server, the new version-specific modules will be in place in less than a minute. 😉 Enjoy the compression!

</>

Categories: Thoughts

Majal

Servant of the Creator happily married to Jehovah's slave girl.