Enable Brotli Compression in Nginx on AlmaLinux 9 with Easy Steps

Posted on

Enable Brotli Compression in Nginx on AlmaLinux 9 with Easy Steps

Enable Brotli Compression in Nginx on AlmaLinux 9 with Easy Steps

This guide will walk you through the process of Enable Brotli Compression in Nginx on AlmaLinux 9. Brotli is a modern compression algorithm designed to provide faster compression speeds and improved compression ratios compared to GZIP. Its open-source nature and compatibility with contemporary web servers and browsers make it an excellent choice for optimizing website performance. Follow these instructions to Enable Brotli Compression in Nginx on AlmaLinux 9 and enhance your website’s speed.

To begin, ensure you’re logged into your AlmaLinux 9 server as a non-root user with sudo privileges. If you haven’t already, you can consult our guide on Initial Server Setup with AlmaLinux 9 for assistance.

A domain name pointed to your server’s IP address is also required for this setup.

Initial Steps To Enable Nginx Brotli Compression

First, update your system’s package index:

sudo dnf update -y

Next, install the necessary packages and dependencies:

# sudo dnf install git unzip socat bash-completion epel-release
# sudo dnf groupinstall "Development Tools" -y

Install Acme.sh on AlmaLinux 9

Acme.sh is a lightweight, shell-based ACME protocol client that simplifies the process of obtaining and managing SSL certificates. Brotli requires HTTPS, so we’ll use Acme.sh to acquire a certificate from Let’s Encrypt. Follow these steps to Enable Brotli Compression in Nginx on AlmaLinux 9 with a secure connection:

# sudo mkdir /etc/letsencrypt
# sudo git clone https://github.com/Neilpang/acme.sh.git
# cd acme.sh
# sudo ./acme.sh --install --home /etc/letsencrypt --accountemail your_email@example.com
# cd ~
# source ~/.bashrc

Replace your_email@example.com with your actual email address.

Verify the installation by checking the Acme.sh version:

acme.sh --version
**Output**
https://github.com/acmesh-official/acme.sh
v3.0.6

Get a TLS certificate from Let’s Encrypt

Use Acme.sh to obtain RSA and ECDSA certificates:

# RSA 2048
$ sudo /etc/letsencrypt/acme.sh --issue --standalone --home /etc/letsencrypt -d example.com --accountemail your_email@example.com --ocsp-must-staple --keylength 2048
# ECDSA/ECC P-256
$ sudo /etc/letsencrypt/acme.sh --issue --standalone --home /etc/letsencrypt -d example.com --accountemail your_email@example.com --ocsp-must-staple --keylength ec-256

Remember to replace example.com and your_email@example.com with your domain and email.

Note: Certificates and keys are stored here:

Install Nginx from the official Nginx repository on AlmaLinux 9

To Enable Brotli Compression in Nginx on AlmaLinux 9 effectively, it is recommended to install the latest mainline version from the official Nginx repository.

First, install yum-utils:

sudo dnf install yum-utils -y

Create the file /etc/yum.repos.d/nginx.repo using your preferred text editor:

sudo vi /etc/yum.repos.d/nginx.repo

Add the following content:

[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

Save and close the file.

Enable the mainline Nginx packages:

sudo yum-config-manager --enable nginx-mainline

Install Nginx:

sudo dnf install nginx -y

Start and enable the Nginx service:

# sudo systemctl enable nginx.service
# sudo systemctl start nginx.service

Verify that Nginx is running:

sudo systemctl status nginx.service
Install Nginx from the official Nginx repository on AlmaLinux 9

Check the Nginx version:

nginx -v
**Output**
nginx version: nginx/1.24.0

Set up Brotli Compression on AlmaLinux 9

To properly Enable Brotli Compression in Nginx on AlmaLinux 9, build the ngx_brotli module as a dynamic module. This approach, available since Nginx version 1.11.5, allows compiling individual modules without recompiling the entire Nginx software.

Download the latest mainline Nginx source code and extract it:

# sudo wget https://nginx.org/download/nginx-1.24.0.tar.gz
# sudo tar zxvf nginx-1.24.0.tar.gz

Note: Ensure that the Nginx package version matches the Nginx source code version.

Remove the Nginx tar package:

sudo rm nginx-1.24.0.tar.gz

Clone Nginx Brotli

Clone the Nginx Brotli compression module:

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

Navigate to the Nginx source code directory:

cd ~/nginx-1.24.0

Install required libraries:

sudo dnf install pcre pcre-devel zlib zlib-devel openssl openssl-devel -y

Compile and Build Brotli

Compile the ngx_brotli module as a dynamic module and copy it to the Nginx modules directory /etc/nginx/modules:

# sudo ./configure --with-compat --add-dynamic-module=../ngx_brotli
# sudo make modules
# sudo cp objs/*.so /etc/nginx/modules

List the files in /etc/nginx/modules to confirm the presence of ngx_http_brotli_filter_module.so and ngx_http_brotli_static_module.so:

ls /etc/nginx/modules
**Output**
**ngx_http_brotli_filter_module.so  ngx_http_brotli_static_module.so**

Set correct permissions for the .so files:

sudo chmod 644 /etc/nginx/modules/*.so

Configure Nginx for Brotli Support on AlmaLinux 9

To Enable Brotli Compression in Nginx on AlmaLinux 9, configure Nginx to utilize the newly built Brotli modules.

Open the Nginx configuration file:

sudo vi /etc/nginx/nginx.conf

Add the following lines at the top of the file to load the Brotli modules:

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

Save and close the file.

Test the Nginx configuration:

sudo nginx -t
**Output**
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Create a document root directory for your domain and an index.html file:

# sudo mkdir -p /var/www/example.com
# sudo -s
# echo "Hello from example.com" >> /var/www/example.com/index.html
# exit

Create Nginx Server Block for Brotli

Create a virtual host configuration file:

sudo vi /etc/nginx/conf.d/example.com.conf

Add the following configuration:

server {
  listen 80;
  server_name example.com;
  return 301 https://$server_name$request_uri;
}

server {
  listen 443 ssl http2;
  server_name example.com;

  root /var/www/example.com;

  # RSA
  ssl_certificate /etc/letsencrypt/example.com/fullchain.cer;
  ssl_certificate_key /etc/letsencrypt/example.com/example.com.key;
  # ECDSA
  ssl_certificate /etc/letsencrypt/example.com_ecc/fullchain.cer;
  ssl_certificate_key /etc/letsencrypt/example.com_ecc/example.com.key;

  brotli on;
  brotli_static on;
  brotli_types text/plain text/css text/javascript application/javascript text/xml application/xml image/svg+xml application/json;
}

Remember to replace example.com with your actual domain.

Save and close the file.

Test the configuration:

sudo nginx -t
**Output**
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Reload Nginx:

sudo systemctl reload nginx.service

Now, visit your site in a web browser and inspect the network tab of the developer tools. Look for Content-Encoding: br in the response headers to confirm that Brotli compression is active.

Conclusion

You have successfully learned how to Enable Brotli Compression in Nginx on AlmaLinux 9. By following these steps, you can significantly improve your website’s performance through efficient compression.

Here are some related articles you might find helpful:

FirewallD Configuration on AlmaLinux 9

Set up Prometheus Server on AlmaLinux 9

Install and Use Flatpak on AlmaLinux 8

Alternative Solutions for Enabling Brotli Compression in Nginx on AlmaLinux 9

While the method described above works, here are two alternative approaches to enabling Brotli compression in Nginx on AlmaLinux 9.

1. Using a Pre-Built Nginx Package with Brotli Module

Instead of compiling the Brotli module yourself, you can use a pre-built Nginx package that already includes the Brotli module. This simplifies the installation process considerably.

Explanation:

Some third-party repositories offer Nginx packages with pre-compiled modules, including Brotli. This avoids the need for manual compilation, reducing the risk of errors and saving time. However, using third-party repositories requires caution, ensuring the source is trustworthy and regularly maintained.

Steps:

  1. Add a Third-Party Repository: Find a reputable repository providing Nginx packages with Brotli support. For example, the Remi repository is often used. You can add it using the following commands (check the Remi documentation for the latest instructions):

    sudo dnf install dnf-utils http://rpms.remirepo.net/enterprise/remi-release-9.rpm
    sudo dnf module enable nginx:remi-safe
  2. Install Nginx: Install Nginx using dnf. It should pull the package from the Remi repository:

    sudo dnf install nginx
  3. Configure Nginx: The Brotli module should already be loaded. Verify this by checking the output of nginx -V (uppercase V). It should list ngx_brotli modules. Then, configure your server block as shown in the original article:

    server {
       listen 443 ssl http2;
       server_name example.com;
    
       root /var/www/example.com;
    
       # SSL Configuration
       ssl_certificate /etc/letsencrypt/example.com/fullchain.cer;
       ssl_certificate_key /etc/letsencrypt/example.com/example.com.key;
    
       brotli on;
       brotli_static on;
       brotli_types text/plain text/css text/javascript application/javascript text/xml application/xml image/svg+xml application/json;
    }
  4. Test and Reload: Test your Nginx configuration and reload the service:

    sudo nginx -t
    sudo systemctl reload nginx.service

Caveats:

  • Trust: Ensure the third-party repository is trustworthy and maintained.
  • Compatibility: Verify that the Nginx version and Brotli module version are compatible with your system.
  • Updates: Monitor the repository for updates to ensure you’re using the latest security patches.

2. Using Docker with a Pre-Configured Nginx Image

Another approach is to use Docker and a pre-configured Nginx image that includes Brotli. This containerization method simplifies deployment and ensures consistent configuration across different environments.

Explanation:

Docker allows you to run applications in isolated containers, ensuring that all dependencies are included and that the application behaves consistently regardless of the host environment. Using a pre-configured Nginx image with Brotli eliminates the need for manual installation and configuration.

Steps:

  1. Install Docker: If you don’t have Docker installed, follow the official Docker documentation to install it on your AlmaLinux 9 system.

  2. Pull a Pre-Configured Nginx Image: Find a Docker image on Docker Hub that includes Nginx with Brotli. A search for "nginx brotli" will yield several options. Choose one that is well-maintained and documented. For example, let’s assume you choose an image called my-nginx-brotli-image. Pull the image:

    docker pull my-nginx-brotli-image
  3. Create an Nginx Configuration File: Create a directory to store your Nginx configuration and create a nginx.conf file within it. This file will override the default configuration in the Docker image. Include the Brotli configuration within your server block:

    events {
        worker_connections 1024;
    }
    
    http {
        include       /etc/nginx/mime.types;
        default_type  application/octet-stream;
    
        sendfile        on;
        keepalive_timeout  65;
    
        gzip  off;  # Disable gzip to avoid conflicts with Brotli
    
        server {
            listen 80;
            server_name example.com;
            return 301 https://$server_name$request_uri;
        }
    
        server {
            listen 443 ssl;
            server_name example.com;
    
            root /usr/share/nginx/html; # Or your website's root
    
            ssl_certificate /etc/nginx/ssl/example.com.crt; # Mount these volumes
            ssl_certificate_key /etc/nginx/ssl/example.com.key; # Mount these volumes
    
            brotli on;
            brotli_static on;
            brotli_types text/plain text/css text/javascript application/javascript text/xml application/xml image/svg+xml application/json;
    
            location / {
                try_files $uri $uri/ =404;
            }
        }
    }

    Note: You’ll need to create directories for your SSL certificates and mount them into the container. Disable gzip to avoid conflicts.

  4. Create a Docker Volume for SSL Certificates: Create a directory to store your SSL certificates:

    mkdir -p /data/nginx/ssl
    # Copy your SSL certificates to this directory
    cp /etc/letsencrypt/example.com/fullchain.cer /data/nginx/ssl/example.com.crt
    cp /etc/letsencrypt/example.com/example.com.key /data/nginx/ssl/example.com.key
  5. Run the Docker Container: Run the Docker container, mounting your configuration file and SSL certificates as volumes:

    docker run -d -p 80:80 -p 443:443 
        -v /path/to/your/nginx.conf:/etc/nginx/nginx.conf 
        -v /data/nginx/ssl:/etc/nginx/ssl 
        -v /path/to/your/website:/usr/share/nginx/html 
        my-nginx-brotli-image

    Replace /path/to/your/nginx.conf, /data/nginx/ssl, and /path/to/your/website with the actual paths on your system.

Caveats:

  • Docker Knowledge: Requires familiarity with Docker concepts.
  • Image Security: Choose a Docker image from a trusted source to avoid security vulnerabilities.
  • Configuration: Ensure your Nginx configuration is compatible with the Docker image’s environment.

These alternative solutions provide different ways to achieve the same goal: Enable Brotli Compression in Nginx on AlmaLinux 9. Choose the method that best suits your needs and technical expertise. Remember to test your configuration thoroughly to ensure Brotli compression is working correctly.

Leave a Reply

Your email address will not be published. Required fields are marked *