目次
Brotli をnginxで試す
2015年にGoogleがオープンソースとして発表した、WEBの圧縮アルゴリズム「Brotli」。
同じくGoogleが発表したZopfliと比べ、圧縮率が20〜26%ほど向上しており、WEBアクセスしてくるユーザーへメリットがあるかなと思い、導入してみました。
[aside type=”normal”] 補足説明をいれる
#spdy対応パッチを適用している関係上、nginx 1.9.7から移せないでいたのですが、セキュリティ観点上あまりよろしくないので、Brotliを導入するついでにアップグレードを行いました。[/aside]
導入方法
既に以前当ブログで紹介した手順で、WEBサーバーを構築していることを前提に、導入方法を説明します。
[aside type=”warning”] 注意事項
Brotliの導入は、spdyやhttp2を導入するときと同様で、HTTPS対応が必須となります。[/aside]
事前準備
nginxのバージョンを1.11系列へアップグレードするため、前回記事で紹介したspdy対応化パッチが利用できなくなります。
ですので、sites-available内の設定ファイルを編集し、spdyの記載を外します。
/etc/nginx/sites-available/hoge.conf
修正前
server { client_max_body_size 20m; etag off; add_header X-Frame-Options SAMEORIGIN; add_header X-XSS-Protection "1; mode=block"; add_header X-Content-Type-Options nosniff; listen 443 ssl spdy http2; ssl on;
修正後
server { client_max_body_size 20m; etag off; add_header X-Frame-Options SAMEORIGIN; add_header X-XSS-Protection "1; mode=block"; add_header X-Content-Type-Options nosniff; listen 443 ssl http2; ssl on;
listen項目から、spdyの記載を削除します。
/etc/nginx/nginx.confの修正
次に、Brotliを有効化するために/etc/nginx.confを修正します。
修正前
include /etc/nginx/mime.types; default_type application/octet-stream; # Load modular configuration files from the /etc/nginx/conf.d directory.
修正後
include /etc/nginx/mime.types; default_type application/octet-stream; brotli on; # Load modular configuration files from the /etc/nginx/conf.d directory.
brotli on;を追加します。
Brotliの導入
まず、GithubからBrotliをcloneしてきます。
cd /usr/local/src git clone https://github.com/google/ngx_brotli.git
次にnginxとOpenSSLの最新版のソースコードをダウンロードし、展開します。
wget https://nginx.org/download/nginx-1.11.9.tar.gz tar zxf nginx-1.11.9.tar.gz wget https://www.openssl.org/source/openssl-1.0.2-latest.tar.gz tar zxf openssl-1.0.2-latest.tar.gz
下記のコマンドを実行して、nginxをビルドします。
cp -p /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.bak cd /usr/local/src/nginx-1.11.9.tar.gz cd /usr/local/src/ngx_brotli && git submodule update --init && cd /usr/local/src/nginx-1.11.9 ./configure --with-http_ssl_module --with-openssl=/usr/local/src/openssl-1.0.2k --add-module=/usr/local/src/ngx_brotli --with-http_v2_module make make install
最後に、設定ファイルが正しく記載されているか確認します。
nginx -t
上記のようなメッセージが末尾に表示されれば成功です。
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
最後にnginxを再起動します。
systemctl restart nginx
確認
外部から、下記のコマンドを実行します。
curl -H "Accept-Encoding:br" -I https://hoge.com
Content-Encoding: brといった表記が表示されれば成功です。
まとめ
なるべくページ表示スピードは速くしたいもの。
これからもどんどんとパフォーマンスチューニングを実施していきたいところですね。