nginx之gzip压缩提高网站速度

目录:javascript


##为啥使用gzip压缩 开启nginx的gzip压缩,网页中的js,css等静态资源的大小会大大的减小从而节约大量的带宽,提升传输效率,给用户快的体验。php

nginx实现gzip

nginx实现资源压缩的原理是经过默认集成的ngx_http_gzip_module模块拦截请求,并对须要作gzip的类型作gzip,使用很是简单直接开启,设置选项便可。。css

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

Request Headers:
Accept-Encoding:gzip,deflate,sdch

Response Headers:
Content-Encoding:gzip
Cache-Control:max-age240

gzip的处理过程java

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

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.htmlnginx

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>演示nginx作gzip压缩</title>
    <script src="./jquery.js" ></script>
</head>
<body>
<img src="./nginx_img.jpeg" style="width: 100px;height: 100px;" />
<h1>nginx实现gzip压缩,减小带宽的占用,同时提高网站速度</h1>
<h1>nginx实现gzip压缩,减小带宽的占用,同时提高网站速度</h1>
<h1>nginx实现gzip压缩,减小带宽的占用,同时提高网站速度</h1>
<h1>nginx实现gzip压缩,减小带宽的占用,同时提高网站速度</h1>
<h1>nginx实现gzip压缩,减小带宽的占用,同时提高网站速度</h1>
<h1>nginx实现gzip压缩,减小带宽的占用,同时提高网站速度</h1>
</body>
</html>

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前的页面请求:浏览器

开启了gzip页面的请求:缓存

注意

  • 图片,mp3通常不须要压缩,由于压缩率比较小
  • 通常压缩text,css,js,xml格式的文件
  • 比较小的文件不须要压缩,有可能还会比源文件更大
  • 二进制文件不须要压缩

原文出处:https://www.cnblogs.com/lisqiong/p/11387083.html

相关文章
相关标签/搜索