nginx中怎么使用gzip压缩提升网站速度

为啥使用gzip压缩

开启nginx的gzip压缩,网页中的JScss等静态资源的大小会大大的减少从而节约大量的带宽,提高传输效率,给用户快的体验。

nginx实现gzip

nginx实现资源压缩的原理是通过默认集成的ngx_http_gzip_module模块拦截请求,并对需要做gzip的类型做gzip,使用非常简单直接开启,设置选项即可。。

gzip生效后的请求头和响应头

request headers: accept-encoding:gzip,deflate,sdch  response headers: content-encoding:gzip cache-control:max-age240

gzip的处理过程

从http协议的角度看,请求头声明acceopt-encoding:gzip deflate sdch(是指压缩算法,其中sdch是google自己家推的一种压缩方式)
服务器-〉回应-〉把内容用gzip压缩-〉发送给浏览器-》浏览器解码gzip->接收gzip压缩内容

gzip的常用配置参数

  • gzip on|off  是否开启gzip

  • gzip_buffers  4k  缓冲(压缩在内存中缓冲几块?每块多大?)

  • gzip_comp_level [1-9]   推荐6  压缩级别,级别越高压缩的最小,同时越浪费cpu资源

  • gzip_disable   正则匹配ua是什么样的uri不进行gzip

  • gzip_min_length  200开始压缩的最小长度,小于这个长度nginx不对其进行压缩

  • gzip_http_version  1.0|1.1开始压缩的http协议版本(默认1.1)

  • gzip_proxied  设置请求者代理服务器,该如何缓存内容

  • gzip_types  text/plain  application/xml  对哪些类型的文件用压缩如txt,xml,html,css

  • gzip_vary  off 是否传输gzip压缩标志

nginx配置gzip

静态页面index.html

nbsp;html&gt;     <meta>   <title>演示nginx做gzip压缩</title>   <script></script> @@##@@ <h1>nginx实现gzip压缩,减少带宽的占用,同时提升网站速度</h1> <h1>nginx实现gzip压缩,减少带宽的占用,同时提升网站速度</h1> <h1>nginx实现gzip压缩,减少带宽的占用,同时提升网站速度</h1> <h1>nginx实现gzip压缩,减少带宽的占用,同时提升网站速度</h1> <h1>nginx实现gzip压缩,减少带宽的占用,同时提升网站速度</h1> <h1>nginx实现gzip压缩,减少带宽的占用,同时提升网站速度</h1>  

nginx的配置

server{     listen 80;     server_name localhost 192.168.0.96;     gzip on;     gzip_buffers 32 4k;     gzip_comp_level 6;     gzip_min_length 200;     gzip_types application/javascript application/x-javascript text/javascript text/xml text/css;     gzip_vary off;     root /users/lidong/desktop/wwwroot/test;     index index.php index.html index.htm;     access_log /users/lidong/wwwlogs/access.log;     error_log /users/lidong/wwwlogs/error.log;     location ~ [^/].php(/|$) {         fastcgi_pass  127.0.0.1:9000;         fastcgi_index index.php;         fastcgi_param script_filename $document_root$fastcgi_script_name;         include    fastcgi_params;     } }

为使用gzip前的页面请求:

nginx中怎么使用gzip压缩提升网站速度

开启了gzip页面的请求:

nginx中怎么使用gzip压缩提升网站速度

nginx中怎么使用gzip压缩提升网站速度

注意

  • 图片,mp3一般不需要压缩,因为压缩率比较小

  • 一般压缩text,css,js,xml格式的文件

  • 比较小的文件不需要压缩,有可能还会比源文件更大

  • 二进制文件不需要压缩

nginx中怎么使用gzip压缩提升网站速度

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享