How to use Brotli in nginx

Brotli is a compression algorithm developed by Google that offers better performance than Gzip in terms of compression ratio and efficiency. Thanks to its higher effectiveness, Brotli can significantly reduce the size of static resources, improving web page loading times.

Enabling Brotli in nginx

To use Brotli with nginx, you need to ensure that the ngx_brotli module is installed. This module is not included by default in nginx and must be added manually.

Installing Brotli

On Debian and Ubuntu-based systems, you can install Brotli using the nginx-extras package:

sudo apt update
sudo apt install -y nginx-extras

If you are using a custom version of nginx, you can manually compile and install the Brotli module:

git clone https://github.com/google/ngx_brotli.git
cd ngx_brotli
git submodule update --init

Then, compile nginx with the Brotli module:

./configure --add-module=../ngx_brotli
make
sudo make install

Configuring nginx for Brotli

After installing Brotli, you need to enable it in the nginx configuration file. Edit the /etc/nginx/nginx.conf file or a virtual server configuration file and add the following directives:

brotli on;
brotli_comp_level 6;
brotli_types text/plain text/css application/javascript application/json image/svg+xml;

The brotli_comp_level parameter controls the compression level (from 1 to 11, with 6 as the default value balanced between compression and speed). The brotli_types directive specifies the file types that will be compressed.

Verification

After applying the changes, restart nginx:

sudo systemctl restart nginx

To verify that Brotli is active, you can use curl:

curl -H "Accept-Encoding: br" -I https://example.com

If the server responds with Content-Encoding: br, it means that Brotli compression is active.

Conclusion

Enabling Brotli in nginx can significantly improve website performance by reducing the size of transferred resources. Although it requires manual configuration, the benefits in terms of loading speed and bandwidth savings justify its implementation.

Back to top