nginx 和 apache 开启gzip压缩

1. nginx 开启压缩方法

gzip on;  
gzip_vary on;    #返回响应头"Vary: Accept-Encoding"  
gzip_min_length  1000;    #开启压缩的最小返回字节数  
gzip_comp_level  6;    #压缩级别,取值值范围1~9  
gzip_types text/plain text/xml text/css application/javascript application/json;  

2. apache 开启压缩方法

<IfModule deflate_module>  
        DeflateCompressionLevel 6    #压缩级别,取值值范围1~9
        AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json
</IfModule>  

apache 使用zlib进行压缩,DeflateCompressionLevel默认值为zlib默认压缩级别6,zlib压缩算法deflate,apache 同样默认返回响应头"Vary: Accept-Encoding"

3. 用curl对比关闭压缩和开启压缩返回的响应头
测试环境: nginx, php-fpm
关闭压缩情况,默认curl请求不压缩

# curl http://127.0.0.1/test.php -v
> GET /test.php HTTP/1.1
> User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.13.6.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2
> Host: 127.0.0.1
> Accept: */*
> 
< HTTP/1.1 200 OK  
< Server: nginx  
< Date: Thu, 19 Mar 2015 03:43:37 GMT  
< Content-Type: text/html  
< Transfer-Encoding: chunked  
< Connection: close  
< Vary: Accept-Encoding  
<  

开启压缩情况,curl添加请求头"Accept-Encoding: gzip"启用压缩

# curl http://127.0.0.1/test.php -v -H "Accept-Encoding: gzip"
> GET /test.php HTTP/1.1
> User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.13.6.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2
> Host: 127.0.0.1
> Accept: */*
> Accept-Encoding: gzip
> 
< HTTP/1.1 200 OK  
< Server: nginx  
< Date: Thu, 19 Mar 2015 03:47:32 GMT  
< Content-Type: text/html  
< Transfer-Encoding: chunked  
< Connection: close  
< Vary: Accept-Encoding  
< Content-Encoding: gzip  
<  

对比返回结果可发现
1) 通过是否返回响应头"Content-Encoding: gzip"可判断是否已经开启压缩
2) 由于没有返回"Content-Length"响应头,所以关闭压缩也返回了"Transfer-Encoding: chunked"响应头
3) 在开启压缩和没有压缩且没有返回"Content-Length",都返回响应头"Transfer-Encoding: chunked"
4) 请求头"Accept-Encoding: gzip"对应响应头会返回"Content-Encoding: gzip"
5) "Vary: Accept-Encoding",缓存服务器(如: varnish)将根据请求头"Accept-Encoding"分别缓存