Improve HTTP compression with Brotli

I’m going to show you how you can get a 10% – 20% improvement in HTTP compression by moving from gzip to brotli.

HTTP compression is a capability that can be built into web servers and web clients to improve transfer speed and bandwidth utilization.

When your client sends a request to the server it will include a header saying which compression formats it will accept, for example:

As you can see it says it will accept gzip, deflate or br compression formats.
The server will respond and if available will compress the result in a supported format:

Here you can see it supports gzip.

Brotli is a new open-source compression format from google that improves on the performance of gzip in many cases. We only care about the HTTP compression.

Warning

Brotli only works on an https connection. Which is a good thing because we all want to encrypt the web, right?

Installing Brotli

apt-get install brotli

Setting up on Apache

Apache has supported brotli since version 2.4.26 by way of the mod_brotli module.
However, I can’t find any information on this so we are installing this module by kjdev

Install the Module

git clone --depth=1 --recursive https://github.com/kjdev/apache-mod-brotli.git
cd apache-mod-brotli
./autogen.sh
./configure
make
install -D .libs/mod_brotli.so /usr/lib/apache2/modules/mod_brotli.so -m 644
cd /etc/apache2/mods-available
echo "LoadModule brotli_module /usr/lib/apache2/modules/mod_brotli.so" > brotli.load

This has added the .load file to the mods available. We need to create an accompanying config file called brotli.conf, adding:

<IfModule brotli_module>
  BrotliCompressionLevel 10
  BrotliWindowSize 22
  AddOutputFilterByType BROTLI text/html text/plain text/css application/x-javascript
<IfModule brotli_module>

Enable the module

a2enmod brotli
service apache2 restart

You should now see in the response header that the page is compressed with brotli (br):

Setting up on Nginx

Google has kindly released an Nginx Brotli module

Download the module

cd /usr/local/src
git clone https://github.com/google/ngx_brotli.git
cd ngx_brotli
git submodule update --init --recursive

Rebuild Nginx with our new module

You should run nginx -V to get your config string and add:

cd /opt/nginx-1.13.1/  (or your own path)
./configure YOUR CONFIG STRING --add-module=/usr/local/src/ngx_brotli
make
make install

Finally, add to your nginx.conf file

http {
    brotli on;
    brotli_static on;
}

In conclusion, the setup for both Apache and Nginx is pretty painless. If the browser does not support brotli it can always fallback to the ever faithful gzip.

You can see current support for brotli here.

If you would like to improve the transfer speed and bandwidth utilization of your site then drop us a message and find out how we can help you.

Share this post