작업실

brotli 압축을 스크립트로 편하게 현재 nginx에 추가하기

컨텐츠 정보

본문

1. 들어가면서


https://www.wsgvet.com/bbs/board.php?bo_table=home&wr_id=494


대략 4년 전에 위와 같은 글을 썼었습니다. 그런데 문제는 nginx를 항상 컴파일 해야된다는 것이었는데요.


dynamic 모듈 설치를 하면 굳이 nginx를 전체 컴파일 하지 않아도 추가가 가능하더라구요.


수동으로 하시려면


https://www.vultr.com/docs/add-brotli-support-to-nginx-on-ubuntu-18-04


위 링크를 추천드립니다.


좀더 편하게 하기 위해서 이 글을 썼겠죠? ^^



2. brotli 압축을 스크립트로 편하게 현재 nginx에 추가하기


https://www.majlovesreg.one/adding-brotli-to-a-built-nginx-instance


위 링크에 있는 내용을 한글로 편하게 설명드립니다.


혹시나 이 글이 오래되어 문제가 생기면 위 링크에서 보시면 됩니다.



먼저 기본적인 패키지를 설치합니다.



sudo apt install build-essential libpcre3-dev zlib1g-dev libpcre3 git


많은 패키지가 설치됩니다.



이제 스크립트를 작성합니다.



sudo nano /usr/local/sbin/mkbrotli


위 명령어 내린 후



#!/bin/bash


# https://www.majlovesreg.one/tag/code/
# https://www.majlovesreg.one/adding-brotli-to-a-built-nginx-instance
# https://github.com/majal/maj-server/tree/master/nginx-modules-brotli


# Install needed development packages if not yet installed in the system
# sudo apt -y install git libpcre3 libpcre3-dev zlib1g zlib1g-dev openssl libssl-dev


# For predefined NGINX version, use:
# ngver=1.17.1


# For passing the version via the command line (i.e.: user@server:~$ ./mkbrotli 1.17.1), use:
ngver=$1


# For automated detection of currently installed NGINX version (not to be used for auto-updating, see hooks in post), use:
# ngver=$(nginx -v 2>&1 | grep -o '[0-9\.]*')


# Get configure parameters of installed NGINX. Not needed if NGINX was configured '--with-compat'.
# Uncomment one of the lines below if the script sucessfully builds modules but NGINX throws a "not binary compatible" error.
# confparams=$(nginx -V 2>&1 | grep -o -- '--prefix='.*)
# confparams=$(nginx -V 2>&1 | grep -o -- '--[^with]'.*)
# confparams=$(nginx -V 2>&1 | grep -- '--' | sed "s/.*' //")
# confparams=$(nginx -V 2>&1 | grep -o -- "--prefix='.*'$")


# To manually set NGINX modules directory:
# moddir=/path/to/modules/directory


# To automatically select NGINX modules directory:
[ -d /usr/share/nginx/modules ] && moddir=/usr/share/nginx/modules
[ -d $(nginx -V 2>&1 | grep -o 'prefix=[^ ]*' | sed 's/prefix=//')/modules ] && moddir="$(nginx -V 2>&1 | grep -o 'prefix=[^ ]*' | sed 's/prefix=//')/modules"
[ -d $(nginx -V 2>&1 | grep -o 'modules-path=[^ ]*' | sed 's/modules-path=//') ] && moddir="$(nginx -V 2>&1 | grep -o 'modules-path=[^ ]*' | sed 's/modules-path=//')"
[ "${moddir}" ] || { echo '!! missing modules directory, exiting...'; exit 1; }


# Set temporary directory and build on it
builddir="$(mktemp -d)"
cd "${builddir}"


echo
echo '################################################################################'
echo
echo "Building Brotli for NGINX ${ngver}"
echo "Temporary build directory: ${builddir}"
echo "Modules directory: ${moddir}"
echo


# Download and unpack NGINX
wget https://nginx.org/download/nginx-${ngver}.tar.gz && { tar zxf nginx-${ngver}.tar.gz && rm nginx-${ngver}.tar.gz; } || { echo '!! download failed, exiting...'; exit 2; }


# Download, initialize, and make Brotli dynamic modules
git clone https://github.com/google/ngx_brotli.git
cd ngx_brotli && git submodule update --init && cd ../nginx-${ngver}
[ "${confparams}" ] && nice -n 19 ionice -c 3 "./configure --add-dynamic-module=../ngx_brotli ${confparams}" || nice -n 19 ionice -c 3 ./configure --with-compat --add-dynamic-module=../ngx_brotli
nice -n 19 ionice -c 3 make modules || { echo '!! configure or make failed, exiting...'; exit 4; }


# Replace Brotli in modules directory
[ -f "${moddir}/ngx_http_brotli_filter_module.so" ] && sudo mv "${moddir}/ngx_http_brotli_filter_module.so" "${moddir}/ngx_http_brotli_filter_module.so.old"
[ -f "${moddir}/ngx_http_brotli_static_module.so" ] && sudo mv "${moddir}/ngx_http_brotli_static_module.so" "${moddir}/ngx_http_brotli_static_module.so.old"
sudo cp objs/*.so "${moddir}/"
sudo chmod 644 "${moddir}/ngx_http_brotli_filter_module.so" || { echo '!! module permissions failed, exiting...'; exit 5; }
sudo chmod 644 "${moddir}/ngx_http_brotli_static_module.so" || { echo '!! module permissions failed, exiting...'; exit 6; }


# Clean up build files
cd "${builddir}/.."
sudo rm -r "${builddir}/ngx_brotli"
rm -r "${builddir}"


echo
echo "Sucessfully built and installed latest Brotli for NGINX ${ngver}"
echo "Modules can be found in ${moddir}"
echo "Next step: Configure dynamic modules and reload/restart NGINX."
echo
echo '################################################################################'
echo


# Start/restart NGINX.
# Not recommended if script is hooked since NGINX is automatically restarted by the package manager (e.g. apt) after an upgrade.
# Restarting NGINX before the upgrade could cause a module version mismatch.
# sudo nginx -t && { systemctl is-active nginx && sudo systemctl restart nginx || sudo systemctl start nginx; } || true
# echo
# systemctl --no-pager status nginx
# echo


위 내용 다 넣고 컨트롤 + O, 엔터, 컨트롤 + X 로  저장 후 닫습니다.



cd /usr/local/sbin/


위 명령어로 스크립트 파일이 있는 곳으로 갑니다.



sudo chmod +x mkbrotli


위 명령어로 스크립트 파일을 실행 가능하게 만듭니다.



sudo nginx -v


위 명령어로 현재 nginx의 버전을 파악합니다.



nginx version: nginx/1.17.10 (Ubuntu)


위와 같이 1.17.10 이 나옵니다. 이게 중요합니다. 이건 자신의 서버환경마다 다르기 때문에 꼭 체크해주세요.



sudo ./mkbrotli 1.17.10


위와 같이 현재 버전을 넣고 실행합니다.



----------------------------------
make[1]: Leaving directory '/tmp/tmp.EK9Y60rUz0/nginx-1.17.10'
Sucessfully built and installed latest Brotli for NGINX 1.17.10
Modules can be found in /usr/lib/nginx/modules
Next step: Configure dynamic modules and reload/restart NGINX.
---------------------------------


성공했다면 위와 같이 뜰 것입니다. Brotli 모듈이 잘 설치가 되어 /usr/lib/nginx/modules 에 있다고 합니다.


이제 Nginx에서 해당 파일을 읽도록 해야 합니다.



3. Nginx에 적용하기


먼저 기본적인 brotli 설정파일을 만듭니다.



sudo nano /etc/nginx/snippets/brotli.conf


위 명령어로 만듭니다.



brotli on;
brotli_comp_level 4;
brotli_static on;
brotli_types application/atom+xml application/javascript application/json application/rss+xml
             application/vnd.ms-fontobject application/x-font-opentype application/x-font-truetype
             application/x-font-ttf application/x-javascript application/xhtml+xml application/xml
             font/eot font/opentype font/otf font/truetype image/svg+xml image/vnd.microsoft.icon
             image/x-icon image/x-win-bitmap text/css text/javascript text/plain text/xml;


위 내용 다 넣고 컨트롤 + O, 엔터, 컨트롤 + X 로  저장 후 닫습니다.


참고로 압축 강도에 대해서는 보통 6으로 잡지만 4로 하면 속도가 더 빨라지는 효과가 있어서 설정했습니다.


서버의 사양이 좋으면 6~7도 괜찮을 것 같습니다.



sudo nano /etc/nginx/nginx.conf


위 명령어로 현재 nginx의 설정파일에 들어갑니다.



제일 위를 보면



user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;


위와 같은 내용이 있는데 바로 밑에



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


위 2줄을 추가합니다.



그리고 61~65번째 줄 정도에 



include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;


위 내용이 있는데 바로 위에



include snippets/brotli.conf;


위 내용을 넣습니다. 컨트롤 + O, 엔터, 컨트롤 + X 로  저장 후 닫습니다.



sudo nginx -t


위 명령어로 설정이 이상없는지 확인합니다.



nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful


위 내용이 나오면 이상없는 것입니다.



sudo service nginx restart


위 명령어로 재시작하면 brotli 압축을 지원하는 웹브라우저에서는 html, js, css 같은 파일들을 압축해서 보내줍니다.



4. Nginx가 업그레이드 되었을 때 자동으로 설치하는 방법


다이나믹 모듈로 설치하면, Nginx가 업그레이드가 되면 무용지물이 됩니다. 다시 이 작업을 해줘야 하는데요.


이것도 쉽게할 수 있습니다.



nano /etc/apt/apt.conf.d/05nginxmodules


위 명령어로 apt와 연결되게 해줍니다.



// Hook to build and install dynamic modules before NGINX upgrades
// Script calls individual build scripts and passes back error codes
// Place this file in /etc/apt/apt.conf.d/


DPkg::Pre-Install-Pkgs {"/usr/local/sbin/nginx-mod-preinstall";};


위 내용 다 넣고 컨트롤 + O, 엔터, 컨트롤 + X 로  저장 후 닫습니다.



nano /usr/local/sbin/nginx-mod-preinstall


위 명령어로 실제 실행되게 해줍니다.



#!/bin/bash
# Call NGINX module build scripts and pass error codes to apt hook


# Get NGINX version to upgrade to
read ngfile < <(grep '/nginx_') || exit 0
ngver=$(echo $ngfile | sed 's/-.*//' | sed 's/.*_//')


# List of build scripts to run:
/usr/local/sbin/mkbrotli $ngver || exit $?
# /usr/local/sbin/mkmodsec $ngver || exit $?
# /usr/local/sbin/mkpagespeed $ngver || exit $?


위 내용 다 넣고 컨트롤 + O, 엔터, 컨트롤 + X 로  저장 후 닫습니다.



sudo chmod +x /usr/local/sbin/nginx-mod-preinstall


위 명령으로 실행가능한 파일로 바꿉니다.


이제 Nginx가 apt로 업그레이드 되어도 자동으로 brotli 다이나믹 모듈을 붙여줄 것입니다.

관련자료

댓글 0
등록된 댓글이 없습니다.
전체 157 / 2 페이지
RSS

최근글


새댓글


알림 0