51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

Nginx网站架构实战——12、nginx gzip压缩提升网站速度

前言:

Nginx网站架构实战------01、Nginx介绍及编译安装:传送门

Nginx网站架构实战------02、Nginx信号量:传送门

Nginx网站架构实战------03、nginx虚拟主机配置:传送门

Nginx网站架构实战------04、nginx日志管理:传送门

Nginx网站架构实战------05、nginx定时任务完成日志切割:传送门

Nginx网站架构实战------06、Location详解之精准匹配:传送门

Nginx网站架构实战------07、Location之正则匹配:传送门

Nginx网站架构实战------08、nginx Rewrite语法详解:传送门

Nginx网站架构实战------09、编译PHP并与nginx整合:传送门

Nginx网站架构实战------10、安装ecshop:传送门

Nginx网站架构实战------11、商城url重写实战:传送门

网页内容的压缩编码与传输速度优化 {#网页内容的压缩编码与传输速度优化}

[code lang="js"]
我们观察news.163.com的头信息
请求:Accept-Encoding:gzip,deflate,sdch
响应:
Content-Encoding:gzip
Content-Length:36093
再把页面另存下来,观察,约10W字节,实际传输的36093字节
原因:就在于gzip压缩上.

原理:
浏览器---请求---->声明可以接受 gzip压缩 或 deflate压缩 或compress 或 sdch压缩
从http协议的角度看--请求头 声明 acceopt-encoding: gzip deflate sdch (是指压缩算法,其中sdch是google倡导的一种压缩方式,目前支持的服务器尚不多)
服务器-->回应---把内容用gzip方式压缩---->发给浏览器
浏览<-----解码gzip-----接收gzip压缩内容----
[/code]

curl测试看是否有gzip {#curl测试看是否有gzip}

[code lang="js"]
未开启之前的curl请求返回的信息
[root@tiejiang html]# curl -I -H "Accept-Encoding: gzip, deflate" "192.168.2.71/tz.php"
HTTP/1.1 200 OK
Server: nginx/1.10.2
Date: Tue, 24 Apr 2018 02:44:19 GMT
Content-Type: text/html; charset=utf-8
Connection: keep-alive
[/code]

gzip配置的常用参数 {#gzip配置的常用参数}

[code lang="js"]
gzip on|off; #是否开启gzip
gzip_buffers 32 4K| 16 8K #缓冲(压缩在内存中缓冲几块? 每块多大?)
gzip_comp_level [1-9] #推荐6 压缩级别(级别越高,压的越小,越浪费CPU计算资源)
gzip_disable "MSIE [1-6]\."; #正则匹配UA 什么样的Uri不进行gzip,IE6对Gzip不怎么友好,不给它Gzip了
gzip_min_length 200k #开始压缩的最小长度(再小就不要压缩了,意义不在)
gzip_http_version 1.0|1.1 #开始压缩的http协议版本(可以不设置,目前几乎全是1.1协议)
gzip_proxied #设置请求者代理服务器,该如何缓存内容
gzip_types text/plain application/xml #对哪些类型的文件用压缩 如txt,xml,html ,css
gzip_vary on|off #是否传输gzip压缩标志

[root@tiejiang ~]# cd /usr/local/nginx/
[root@tiejiang nginx]# vim conf/nginx.conf #因为要全局生效,所以直接在server这里写gzip的信息。
server {
listen 80;
server_name localhost;

gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.0;
gzip_comp_level 2;
gzip_types text/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
gzip_vary off;
[/code]

开启gzip后curl检测返回信息 {#开启gzip后curl检测返回信息}

[code lang="js"]
[root@tiejiang nginx]# ./sbin/nginx -s reload
[root@tiejiang nginx]# curl -I -H "Accept-Encoding: gzip, deflate" "192.168.2.71/tz.php"
HTTP/1.1 200 OK
Server: nginx/1.10.2
Date: Tue, 24 Apr 2018 02:45:41 GMT
Content-Type: text/html; charset=utf-8
Connection: keep-alive
Content-Encoding: gzip
[/code]

赞(4)
未经允许不得转载:工具盒子 » Nginx网站架构实战——12、nginx gzip压缩提升网站速度