Как установить NGINX со сжатием Brotli и Gzip в Ubuntu
Введение
NGINX - это проект с открытым исходным кодом, созданный Игорем Сысоевым и выпущенный еще в 2004 году. NGINX обычно используется для балансировки нагрузки, обратного проксирования и в качестве веб-сервера.gzip - это утилита сжатия данных без потерь. Когда пользователь посещает веб-сайт, такие ресурсы, как изображения, jаvascript, таблицы стилей и другие, обычно сжимаются с помощью gzip.
Brotli - это новый алгоритм сжатия, использующий предопределенный словарь с общими ключевыми словами и фразами как на стороне клиента, так и на стороне сервера. Поддерживается всеми основными браузерами.
Предпосылки
- Сервер под управлением Ubuntu 16.04 / 18.04 / 18.10 / 19.04.
- Корневой доступ
- Предустановленный NGINX (опционально)
Шаг 1 - Установите и настройте NGINX
Шаг 1.1 - Предустановочные шаги
Проверьте версию Ubuntu:root@example-server:~# lsb_release -ds
Ubuntu 18.04.2 LTS
apt update && apt upgrade -y
Шаг 1.2 - Сборка NGINX из исходного кода
NGINX написан на C, поэтому нам нужно установить инструменты компилятора.apt install -y build-essential git tree
wget https://nginx.org/download/nginx-1.17.0.tar.gz && tar zxvf nginx-1.17.0.tar.gz
PCRE
wget https://ftp.pcre.org/pub/pcre/pcre-8.43.tar.gz && tar xzvf pcre-8.43.tar.gz
Zlib
wget https://www.zlib.net/zlib-1.2.11.tar.gz && tar xzvf zlib-1.2.11.tar.gz
OpenSSL
wget https://www.openssl.org/source/openssl-1.1.1c.tar.gz && tar xzvf openssl-1.1.1c.tar.gz
Brotli
#Before downloading Brotli you can check and this repo: https://github.com/yverry/ngx_brotli.git, both of the repositories are maintained, you can choose which of the repo to use.
git clone https://github.com/eustas/ngx_brotli.git
cd ngx_brotli
git submodule update --init --recursive
apt update
выполняется после добавления репозитория.add-apt-repository -y ppa:maxmind/ppa
apt update && apt upgrade -y
apt install -y perl libperl-dev libgd3 libgd-dev libgeoip1 libgeoip-dev geoip-bin libxml2 libxml2-dev libxslt1.1 libxslt1-dev
Шаг 1.3 - Скомпилируйте NGINX с Brotli
Войдите в папку NGINX.cd ~/nginx-1.17.0
./configure --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --user=nginx --group=nginx --build=Ubuntu --builddir=nginx-1.17.0 --with-select_module --with-poll_module --with-threads --with-file-aio --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_addition_module --with-http_xslt_module=dynamic --with-http_image_filter_module=dynamic --with-http_geoip_module=dynamic --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_auth_request_module --with-http_random_index_module --with-http_secure_link_module --with-http_degradation_module --with-http_slice_module --with-http_stub_status_module --with-http_perl_module=dynamic --with-perl_modules_path=/usr/share/perl/5.26.1 --with-perl=/usr/bin/perl --http-log-path=/var/log/nginx/access.log --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --with-mail=dynamic --with-mail_ssl_module --with-stream=dynamic --with-stream_ssl_module --with-stream_realip_module --with-stream_geoip_module=dynamic --with-stream_ssl_preread_module --with-compat --with-pcre=../pcre-8.43 --with-pcre-jit --with-zlib=../zlib-1.2.11 --with-openssl=../openssl-1.1.1c --with-openssl-opt=no-nextprotoneg --with-debug --add-module=../ngx_brotli --sbin-path=/usr/sbin/nginx
make && make install
ln -s /usr/lib/nginx/modules /etc/nginx/modules-enabled
nginx -V
nginx version: nginx/1.17.0 (Ubuntu)
built by gcc 8.3.0 (Ubuntu 8.3.0-6ubuntu1)
built with OpenSSL 1.1.1c 28 May 2019
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --user=nginx --group=nginx --build=Ubuntu --builddir=nginx-1.17.0 --with-select_module --with-poll_module --with-threads --with-file-aio --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_addition_module --with-http_xslt_module=dynamic --with-http_image_filter_module=dynamic --with-http_geoip_module=dynamic --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_auth_request_module --with-http_random_index_module --with-http_secure_link_module --with-http_degradation_module --with-http_slice_module --with-http_stub_status_module --with-http_perl_module=dynamic --with-perl_modules_path=/usr/share/perl/5.26.1 --with-perl=/usr/bin/perl --http-log-path=/var/log/nginx/access.log --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --with-mail=dynamic --with-mail_ssl_module --with-stream=dynamic --with-stream_ssl_module --with-stream_realip_module --with-stream_geoip_module=dynamic --with-stream_ssl_preread_module --with-compat --with-pcre=../pcre-8.43 --with-pcre-jit --with-zlib=../zlib-1.2.11 --with-openssl=../openssl-1.1.1c --with-openssl-opt=no-nextprotoneg --with-debug --add-module=../ngx_brotli --sbin-path=/usr/sbin/nginx
Шаг 1.4 - Создание пользователя и группы
Пользователь создан без домашнего каталога и с отключенными логином и паролем.adduser --system --home /nonexistent --shell /bin/false --no-create-home --disabled-login --disabled-password --gecos "nginx user" --group nginx
service nginx configtest
nginx -t
nginx: [emerg] mkdir() "/var/cache/nginx/client_temp" failed (2: No such file or directory)
Создайте каталоги кэша NGINX, каталоги по умолчанию и установите разрешения.
mkdir /var/cache/nginx/client_temp
mkdir /var/cache/nginx/fastcgi_temp
mkdir /var/cache/nginx/proxy_temp
mkdir /var/cache/nginx/scgi_temp
mkdir /var/cache/nginx/uwsgi_temp
chmod 700 /var/cache/nginx/*
chown nginx:root /var/cache/nginx/*
mkdir /etc/nginx/conf.d
mkdir /etc/nginx/snippets
mkdir /etc/nginx/sites-available
mkdir /etc/nginx/sites-enabled
chmod 640 /var/log/nginx/*
chown nginx:root /var/log/nginx/access.log /var/log/nginx/error.log
nginx -t
service nginx configtest
Шаг 1.5 Включите NGINX для запуска при загрузке
Сначала создайте системный файл.nano /etc/systemd/system/nginx.service
[Unit]
Description=Nginx - high performance web server
Documentation=https://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target
[Service]
Type=forking
PIDFile=/var/run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t -c /etc/nginx/nginx.conf
ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s TERM $MAINPID
[Install]
WantedBy=multi-user.target
systemctl enable nginx.service
systemctl start nginx.service
Чтобы проверить, работает ли NGINX, вы можете посетить свой IP-адрес через браузер.
Откройте в веб-браузере:
http://server_domain_name_or_IP/
Как найти публичный IP-адрес вашего сервера
Если вы не знаете, что такое публичный IP-адрес вашего сервера, существует много способов узнать ваш публичный IP-адрес.
Из командной строки вы можете использовать
ip
инструменты, чтобы получить свой адрес, набрав:ip addr show dev eth0 | grep "inet" | awk '{ print $2 }'
Шаг 2 - Настройте NGINX для использования Brotli и Gzip
Gzip используется для браузеров, которые не поддерживают Brotli.Теперь у нас установлены все необходимые компоненты.
Отредактируйте файл конфигурации NGINX и добавьте следующие строки в NGINX:
nano /etc/nginx/nginx.conf
В настоящее время с удаленными комментариями http-блок NGINX выглядит следующим образом:
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include /etc/nginx/mime.types;
default_type application/octet-stream;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
ssl_prefer_server_ciphers on;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
gzip on;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
gzip on;
и добавьте следующую конфигурацию:http {
....
gzip on;
# Compression level (1-9).
gzip_comp_level 5;
# Don't compress anything that's already small
gzip_min_length 256;
# Compress data even for clients that are connecting to us via proxies
gzip_proxied any;
# Tell proxies to cache both the gzipped and regular version of a resource
# whenever the client's Accept-Encoding capabilities header varies;
gzip_vary on;
# Compress all output labeled with one of the following MIME-types.
gzip_types
application/atom+xml
application/geo+json
application/jаvascript
application/json
application/ld+json
application/manifest+json
application/rdf+xml
application/rss+xml
application/vnd.ms-fontobject
application/wasm
application/x-web-app-manifest+json
application/xhtml+xml
application/xml
font/otf
image/bmp
image/svg+xml
text/cache-manifest
text/calendar
text/css
text/jаvascript
text/markdown
text/plain
text/vcard
text/vnd.rim.location.xloc
text/vtt
text/x-component
text/x-cross-domain-policy;
#Brotli documentation https://github.com/eustas/ngx_brotli#configuration-directives
brotli on;
#Because brotli_static is like gzip_static before it, is only for files served via nginx - it will only detect .br files when served via the filesystem
brotli_static on;
# For static files, we gonna use 11, but if there is dynamic content we should use 4(smaller response and less time to compress)
brotli_comp_level 11;
#Brotli is used only for some file types, because files like jpeg, png,mp4 are already compressed, if we use Brotli on jpeg/png, the jpeg/png is already compressed, and it will get bigger rather than smaller.
brotli_types
application/atom+xml
application/geo+json
application/jаvascript
application/json
application/ld+json
application/manifest+json
application/rdf+xml
application/rss+xml
application/vnd.ms-fontobject
application/wasm
application/x-font-opentype
application/x-font-truetype
application/x-font-ttf
font/eot
font/opentype
font/otf
image/bmp
image/svg+xml
image/vnd.microsoft.icon
image/x-icon
image/x-win-bitmap
text/cache-manifest
text/css
text/jаvascript
text/markdown
text/plain
text/x-component
text/x-cross-domain-policy
text/xml
application/x-jаvascript
application/x-web-app-manifest+json
application/xhtml+xml
application/xml
application/xml+rss;
....
}
Перезапустите NGINX, чтобы внести необходимые изменения:
service nginx restart
Заключение
Если вы успешно выполнили вышеуказанные шаги, теперь на вашем сервере должен быть установлен NGINX с включенным сжатием Brotli и Gzip. Теперь вы можете загружать файлы своих сайтов в/var/www/html
каталог и выполнять тестирование с новыми алгоритмами сжатия.
Комментариев 0