Как установить brotli ubuntu

Внедряем Brotli с помощью Nginx — экономим байты почти бесплатно

Эта статья пригодится всем, кто неравнодушен к скорости доставки своего веб-приложения пользователю и хочет выжать дополнительные миллисекунды и килобайты экономии.

Что такое brotli?

Это новый стандарт компрессии данных, разработанный Google. Хорошее описание и сравнение с другими алгоритмами есть у Clouflare.

В двух словах: это новый вид сжатия, который оптимизирован для веб-применений (HTML, CSS, JS и т.д.) за счет использования статического словаря и других оптимизаций. Он показывает сравнимую скорость при лучшем сжатии по сравнению с gzip и намного лучшее сжатие при максимальных настройках (и очень низкой скорости). Подробное исследования скорости и коэффициентов компрессии смотрите в указанной статье от Cloudflare.

Я приведу небольшую таблицу с реальными файлами (JS, CSS) живого веб-сайта. Перед сжатием все файлы были минифицированы. Сравнивать будем zopfli (i500) — совместимый с gzip компрессор и brotli с настройкой сжатия 11 (максимум).

Тип файлов и сжатие Размер (байт) Размер (в % от исходного)
CSS исходные файлы 334 937 100%
CSS zopfli 60 771 18,1%
CSS brotli 56 168 16,7%
JS исходные файлы 477 393 100%
JS zopfli 149 905 31,4%
JS brotli 135 766 28,4%

Из этой таблицы можно прикинуть экономии для варианта использования в static режиме (когда файлы сжаты заранее и отдаются Nginx как есть). Для компрессии динамического контента все немного сложнее — нужно сохранять баланс между степенью компрессии и временем сжатия.

Для себя я вывел следующее правило: за счет zopfli можно сэкономить примерно 10% по сравнению с gzip 9, а brotli даёт еще 10% экономии.

Поддержка браузерами

Достаточно хорошая, чтобы использовать уже сейчас. По данным caniuse.com это около 50% аудитории. На самом деле, думаю побольше, потому что brotli поддерживается в Chrome 51+, Firefox 47+ и мобильным Chrome. Важное дополнение: так как brotli несовместим с gzip, он поддерживается только для HTTPS-ресурсов. Это чтобы всякие тупые прокси не побили контент.

Посмотреть поддержку клиентом просто: он должен указать в заголовке запроса accept-encoding br, что и означает «brotli». Например, так:

Включаем поддержку в Nginx

К сожалению, пока нет стандартного модуля для поддержки brotli в Nginx. Но нас этим не остановишь: есть сторонние модули от самого Google и от Cloudflare. Мы будем использовать вариант от Google, так как он нормально документирован и имеет все нужные возможности.

Здесь нужно определиться, как вы будете использовать brotli: только в статическом варианте (brotli_static) или в динамическом (сжатие на лету — brotli). Сборка модуля в режиме brotli_static проще, так как не требуется библиотека для сжатия brotli: libbrotli.

Используем готовый пакет из PPA

hda-me/+archive/ubuntu/nginx-stable. Из PPA мы получаем Nginx Stable ветки с множеством дополнительных модулей. Большинство из них динамические, то есть их можно подключать по желанию. Если вас устраивает этот вариант, можете ставить и переходить к конфигурации.

Собираем Nginx самостоятельно

В этом случае процесс аналогичен сборке Nginx с любыми другими модулями. Сначала качаем и распаковываем исходники Nginx (указана актуальная на момент публикации версия).

Получаем код модуля ngx_brotli:

Если мы хотим использовать brotli в динамическом режиме, качаем libbrotli:

И собираем (в папке libbrotli):

Или можем установить libbrotli из PPA, указанного ранее.

Если нам нужен только brotli_static, перед сборкой Nginx говорим об этом:

Читайте также:  коды для boku no roblox remastered

Теперь идём в папку с исходниками Nginx и собираем его (c опцией —add-module=[путь до ngx_brotli]):

Далее можно установить Nginx (make install) или собрать в deb-пакет:

Конфигурация Nginx

Итак, у нас наконец есть Nginx с поддержкой brotli. Для использования статических brotli-файлов (сжатых заранее), достаточно включить в конфиг nginx.conf (секция http) одну директиву:

Теперь nginx будет искать версию файла с суффиксом .br, если клиент заявляет о поддержке brotli. Если не найдёт, то будет работать модуль gzip_static (если включён).

Для активации динамического режима указываем следующие параметры:

Здесь мы используем уровень сжатия 6, потому что он имеет хорошее соотношение качество/производительность. Уровень сжатия будет лучше, чем с gzip 9. Далее указаны MIME-типы контента для сжатия. Уточните конфигурацию ваших MIME-типов на сервере, чтобы сжатие применялось к нужным типам контента. Brotli имеет приоритет перед gzip, поэтому будет использоваться в случае поддержки (также для статического режима).

Проверить работу brotli просто: посмотрите на заголовки ответа, там должно быть:

На этом всё: успехов в оптимизации и используйте новые технологии!

P. S. Если вы используете Ubuntu 16.04, то установить утилиту для консольного сжатия brotli очень просто:

Источник

Как установить Brotli Module для Nginx в Ubuntu 20.04 LTS

Как установить Brotli Module для Nginx в Ubuntu 20.04 LTS

В этой статье предполагается, что у вас есть хотя бы базовые знания Linux, вы знаете, как использовать оболочку, и, что наиболее важно, вы размещаете свой сайт на собственном VPS. Установка довольно проста и предполагает, что вы работаете с учетной записью root, в противном случае вам может потребоваться добавить ‘ sudo ‘ к командам для получения привилегий root. Я покажу вам пошаговые инструкции по включению Brotli Compression на Nginx. Вы можете следовать тем же инструкциям для Ubuntu 18.04, 16.04 и любого другого дистрибутива на основе Debian, например Linux Mint.

Установите модуль Brotli для Nginx в Ubuntu 20.04 LTS Focal Fossa

Шаг 1. Во-первых, убедитесь, что все ваши системные пакеты обновлены, выполнив следующие apt команды в терминале.

Шаг 2. Установка Nginx на Ubuntu 20.04.

Nginx доступен в репозиториях Ubuntu по умолчанию. Для его установки выполните следующую команду:

После завершения установки запустите команды, которые позволят Nginx автоматически запускаться при запуске вашего сервера:

Шаг 3. Установка модуля Brotli для Nginx.

Теперь мы запускаем следующую команду, чтобы загрузить и установить модуль Nginx Static Brotli:

Шаг 4. Настройте Nginx.

Создаем конфигурацию, чтобы NGINX использовал модуль Brotli:

Теперь добавьте конфигурацию Brotli:

Затем запустите службу Nginx, используя следующую команду:

Шаг 5. Тестирование модуля Brotli.

Теперь проверьте, включен ли модуль Brotli, выполнив следующую команду:

Источник

How to install Brotli on Ubuntu 17.04

How to install Brotli on Ubuntu 17.04

The Brotli is a generic purpose lossless compression algorithm that compresses the data using a combination of modern variant of lz77 algorithm, and huffman coding. It is similar in speed with deflate but offers more dense compression.This tutorial explains the installation procedure of Brotli on Ubuntu.

Installation procedure

To begin with the installation procedure, add the repo in the target system using the following command.

The system is updated with the added repositories. Install the Brotli package by executing the following command.

Читайте также:  Как удовлетворить мужчину близнеца

For using the package, execute the following command. It lists the options that can be used with brotli.

To remove the package, run the following command to remove the Brotli package and all of its repositories.

Wasn’ t that an easy installation procedure? Brotli has a compression ratio comparable to the currently available general-purpose compression methods.

Comments ( 0 )

No comments available

Frequently asked questions ( 5 )

How to check version of Brotli?

what is the syntax of brotli?

what is the supported languages of brotli?

the supported languages of brotli is «C».

which command to remove the package of Brotli in ubuntu?

how to check the options in brotli in ubuntu?

= 5 || postCtrl.tagPost[‘tutorials’].current_page» ng-bind-html=»postCtrl.showtype1[‘tutorials’] | unsafe»>

= 5 || postCtrl.tagPost[‘forums’].current_page» ng-bind-html=»postCtrl.showtype1[‘forums’] | unsafe»>

= 5 || postCtrl.tagPost[‘news’].current_page» ng-bind-html=»postCtrl.showtype1[‘news’] | unsafe»>

The media folder above has 777 permissions, I see your share in the tutorial has the shared folder in the «home» directory, I need the shares to be linked to the folder path as above, without needing to be the root user on the client machine to mount the shares?

Any advice on this will be greatly appreciated.

Источник

Add Brotli support to Nginx on Ubuntu 18.04

Brotli (br) is a new open source compression algorithm, developed by Google as an alternative to Gzip, Zopfli and Deflate. It is formally defined in Internet Engineering Task Force (IETF) as RFC 7932. Google’s case study on Brotli has shown compression ratios of up to 26% smaller than current methods, with less CPU usage.

Nginx does not have official support but there is a third-party module developed by Google called ngx_brotli that we can use to add support to Nginx.

This guide will show you how to add Brotli support to Nginx on a fresh Ubuntu 18.04 LTS Vultr instance.

NOTE: This guide will use johndoe as an example user and example.com as an example domain. Replace them according to your names.

Requirements

Before you begin

Check the Ubuntu version.

Create a new non-root user account with sudo access and switch to it.

NOTE: Replace johndoe with your username.

Update your operating system’s software.

Set up the timezone.

Install required build tools and packages.

Brotli requires you to set up and use HTTPS. In this part we will get a trusted certificate from Let’s Encrypt.

Download and install Acme.sh.

After running the commands above, your certificates and keys will be in the following locations:

Step 2 – Install Nginx from the official Nginx repository

Download and install the latest mainline Nginx from the official Nginx repo.

Enable and start Nginx.

Step 3 – Download and compile the Brotli source code

After installing Nginx, we need to build the Brotli module ( ngx_brotli ) as a dynamic Nginx module. From Nginx version 1.11.5 it is possible to compile individual dynamic modules without compiling the complete Nginx software. In the next few steps, we will build the Brotli module as dynamic without compiling the complete Nginx.

Download the latest version of the mainline Nginx source code and extract it.

NOTE: It is very important that version numbers of the Nginx package and Nginx source code match. If you installed Nginx 1.15.2 from the official Nginx repository, then you must download the same version of the source code, 1.15.2 in this case.

Clone ngx_brotli from GitHub.

Читайте также:  обои с неймаром в псж на телефон

Navigate to the Nginx source code directory.

Download required libraries.

Step 4 – Configure Nginx

We are ready to configure Brotli support in Nginx.

Run sudo vim /etc/nginx/nginx.conf and add the following two directives at the top of the file to load new Brotli modules.

Test the configuration.

Create a document root directory for example.com and create index.html with some content in it.

Populate it with the following configuration.

Test the configuration.

Visit your site in your web browser and open the network tab of developer tools. You will see Content-Encoding: br in the response headers. That is the indicator that Brotli compression is working.

You have enabled Brotli compression on your web server.

Источник

⚙️ How to install Brotli module for Nginx on Ubuntu 20.04+

Introduction

Fasten your seatbelts, because we’re starting! 🚀 I will show you a fast automated way (which I use myself) and more detailed (and manual).

📝 Table of contents

⚡️ Quick guide

Check, that you have Python (at least version 3.5 ) and Ansible (I recommend the 2.9 version) on your local machine.

Next, download ZIP archive (or git clone ) Useful playbooks GitHub repository and go to the downloaded (or cloned) folder.

🚚 Useful Ansible playbooks for easily deploy your website or webapp to absolutely fresh remote virtual server and automation many processes. Only 3 minutes from the playbook run to complete setup server and start it.

Exit fullscreen mode

This playbook will determine the installed version of Nginx itself, download the necessary dependencies, build and configure Brotli module and add the load_module section to Nginx configuration ( /etc/nginx/nginx.conf ).

📚 A long, but detailed guide

If you like longer and more detailed stories, as well as I do, let’s start with a simple step: login to your remote virtual server running on Ubuntu 20.04+ (via SSH, for example).

✅ Install dependencies

Exit fullscreen mode

If you already have some packages (from the list above) installed, you do not need to install them again.

✅ Download the source code

First, download and unpack Nginx:

Exit fullscreen mode

Second, git clone Brotli module from official Google repository:

Exit fullscreen mode

The folder structure should look like this at the moment:

Exit fullscreen mode

✅ Build Brotli module with Nginx

Exit fullscreen mode

☝️ Please wait, this may take some time!

Exit fullscreen mode

✅ Add Brotli config

Add load_module section to the start of Nginx config:

Exit fullscreen mode

Now, add the Brotli config:

Exit fullscreen mode

Restart Nginx service and we’re done. It just works! 🎉

💬 Questions for better understanding

Photos/Images by

If you want more — write a comment below & follow me. Thx! 😘

Discussion (5)

Then the path of modules was different for my install and was /usr/lib/nginx/modules (not /usr/share).

Hi, Alan. Great addition to the article! 👍

Unfortunately, (in my practice) it was not necessary to do the actions you described.

Источник

Обучающий проект