在Linux系统上安装了Nginx Web服务器,如何为静态网站资源(如HTML/JS/CSS/JSON文件)启用gzip和Brotli压缩,以加快网页加载速度,以下提供方法。Gzip和Brotli是主流Web浏览器支持的最流行的压缩算法。安装及配置服务器请参考CentOS 7系统源码安装和配置Nginx服务器一文。
安装ngx_brotli - Brotli的Nginx模块 ngx_brotli是Nginx模块,它使用Brotli进行压缩任务,它是一组两个模块: 1]、ngx_brotli过滤器模块 - 用于即时压缩响应。 2]、ngx_brotli静态模块 - 用于提供预压缩文件。 1、在Ubuntu上安装ngx_brotli模块 以下命令用于在Ubuntu系统上安装ngx_brotli模块: sudo apt-add-repository -y ppa:hda-me/nginx-stable sudo apt-get update sudo apt-get install brotli nginx nginx-module-brotli 重启Nginx以使用Brotli: sudo systemctl restart nginx 2、在CentOS 7上安装ngx_brotli模块 我们将使用GetPageSpeed extras YUM存储库在CentOS 7服务器上为Brotli安装Nginx模块: sudo yum -y install https://extras.getpagespeed.com/release-el7-latest.rpm sudo yum -y install nginx nginx-module-nbr 安装后需要启用该模块,编辑nginx配置文件 - /etc/nginx/nginx.conf并在顶部附近添加下面行: load_module modules/ngx_http_brotli_filter_module.so; load_module modules/ngx_http_brotli_static_module.so; 下面是一个Nginx配置的示例截图:
配置Nginx以使用Brotli/gzip压缩 现在我们已经安装了压缩模块,打开你网站的Nginx配置文件并添加以下行: # gzip gzip on; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_types text/plain text/css text/xml application/json application/javascript application/xml+rss application/atom+xml image/svg+xml; # brotli brotli on; brotli_comp_level 6; brotli_types text/xml image/svg+xml application/x-font-ttf image/vnd.microsoft.icon application/x-font-opentype application/json font/eot application/vnd.ms-fontobject application/javascript font/otf application/xml application/xhtml+xml text/javascript application/x-javascript text/plain application/x-font-truetype application/xml+rss image/x-icon font/opentype text/css image/x-win-bitmap; Nginx Web服务器需要重新启动才能压缩静态内容: sudo systemctl restart nginx
在网站上测试Brotli/gzip压缩 支持brotli的浏览器在accept-encoding请求头中发送'br'和'gzip',比如: $ curl -IL https://computingforgeeks.com -H "Accept-Encoding: br" HTTP/2 200 date: Sat, 20 Apr 2019 20:06:28 GMT content-type: text/html; charset=UTF-8 vary: Accept-Encoding ... x-frame-options: SAMEORIGIN x-xss-protection: 1; mode=block x-content-type-options: nosniff expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct" server: cloudflare cf-ray: 4ca9bd24fdfecb79-MBA content-encoding: br 用curl检查gzip编码: $ curl -IL https://computingforgeeks.com -H "Accept-Encoding: gzip" HTTP/2 200 date: Sat, 20 Apr 2019 20:06:28 GMT content-type: text/html; charset=UTF-8 vary: Accept-Encoding ... x-frame-options: SAMEORIGIN x-xss-protection: 1; mode=block x-content-type-options: nosniff expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct" server: cloudflare cf-ray: 4ca9bd24fdfecb79-MBA content-encoding: gzip 如果你的Web服务器上启用了brotli,将获得brotli压缩格式的响应,还可以使用Web浏览器检查内容编码,具体如下: Inspect > Network > Headers > "Response Headers" > "Content-Encoding" header(检查>网络>标题>“响应标题”>“内容编码”标题):
至此,在启用静态网站资源压缩后,将能大大的加快网站加载速度。
相关主题 |