Enabling Brotli Compression on NGINX

Enabling Brotli compression on your NGINX server can improve pagespeed and reduce used bandwidth. In the following, we'll show you how to enable Brotli compression on NGINX.

Step 1: Install the Brotli module for NGINX

The first step is to install the Brotli module for NGINX. There are two ways to do this: compile NGINX from source with the ngx_brotli module, or install it using a package manager. We will have a look at both options now:

Compiling NGINX from source with the ngx_brotli module

To compile NGINX from source with the ngx_brotli module, follow these steps:

  1. Download the latest version of NGINX and the ngx_brotli module from their respective websites:
wget https://nginx.org/download/nginx-1.20.1.tar.gz
wget https://github.com/google/ngx_brotli/archive/refs/tags/v1.0.2.tar.gz

Replace nginx-1.20.1 with the version of NGINX you want to install.

  1. Extract the NGINX and ngx_brotli archives:
tar -xzf nginx-1.20.1.tar.gz
tar -xzf v1.0.2.tar.gz
  1. Change to the NGINX source directory and configure NGINX with the ngx_brotli module:
cd nginx-1.20.1
./configure --with-compat --add-dynamic-module=../ngx_brotli-1.0.2
  1. Build and install NGINX:
make modules
sudo make install

Installing the Brotli module using a package manager

To install the Brotli module using a package manager, follow these steps:

  1. Update your package manager's repository information:
sudo apt update
  1. Install NGINX with the Brotli module:
sudo apt install nginx nginx-module-brotli

If you're using a different package manager like yum, replace apt with the appropriate command.

Step 2: Enable Brotli compression in your NGINX configuration

Once you've installed the Brotli module, the next step is to enable Brotli compression in your NGINX configuration. To do this, edit your NGINX configuration file (usually located at /etc/nginx/nginx.conf) and add the following lines to the http block:

# Enable Brotli compression
brotli on;
brotli_comp_level 4;
brotli_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript;

The brotli on; line enables Brotli compression, while brotli_comp_level r; sets the compression level to 4 (which is what we recommend). The brotli_types directive specifies the MIME types that should be compressed using Brotli. You can add or remove MIME types as needed.

Here's an example http block with Brotli compression enabled:

http {
# ... other configuration ...
# Enable Brotli compression
brotli on;
brotli_comp_level 4;
}

Reload NGINX

Eventually, you want to reload NGINX to apply the changes you've made to your configuration file:

sudo nginx -t && sudo nginx -s reload

Test Brotli Compression

Once you've installed the Brotli module and configured Apache to use it, you should test whether Brotli compression is working correctly. You can use our Brotli checker to check your website and see if it worked.