Nginx開啟gzip壓縮演示

一、介紹

Nginx對靜態資源的壓縮就是在服務端進行壓縮傳輸到瀏覽器端進行解壓,這個壓縮和解壓的過程中減少中間網絡傳輸的消耗。就是減少服務端帶寬資源的消耗還有減少傳輸的文件大小從而實現傳輸的實時性。

對於壓縮我們可以啟用Nginx的gizp壓縮設置。


二、gizp配置

#開啟gzip
gzip on;
# gzip 壓縮級別
gzip_comp_level 2;
# 啟用gzip壓縮的最小文件
gzip_min_length 1k;
# 進行壓縮的文件類型。
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;

更多設置參考:Nginx文檔gzip相關參數設置

三、演示

首先我在服務器準備好了演示使用的圖片demo.jpg

Nginx開啟gzip壓縮演示

接下來我們前往/etc/nginx/conf.d/新建test.conf進行設置

server {
listen 80;
server_name localhost;
sendfile on;
#charset koi8-r;
access_log /var/log/nginx/host.access.log main;
location ~ .*\.(jpg|gif|png)$ {
gzip off;
gzip_http_version 1.1;
gzip_comp_level 2;
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
root /opt/app/demo/images;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 404 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
# proxy the PHP/> #
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP/> #
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}

此時設置gzip off 我們訪問該圖片:

Nginx開啟gzip壓縮演示

該圖片資源大小為749KB

接下來我們開啟gzip

location ~ .*\.(jpg|gif|png)$ {
gzip on;
gzip_http_version 1.1;
gzip_comp_level 2;
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
root /opt/app/demo/images;
}

reload nginx:

nginx -s reload -c /etc/nginx/nginx.conf

Nginx開啟gzip壓縮演示

現在該圖片傳輸資源大小被壓縮為747KB

可以看到確實有壓縮了但是似乎壓縮的比並不理想

事實上gzip對文本的壓縮更為顯著,對圖片的壓縮比率並不是很理想

我們同樣對文本文件壓縮設置來測試一下壓縮的比例:

 我們在text.conf中增加這一段location ~ .*\.(txt|xml)$ {
gzip off;
gzip_http_version 1.1;
gzip_comp_level 2;
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
root /opt/app/demo/doc;
}

然後在/opt/app/demo/doc 中準備好文本文件

reload Nginx後在gzip off時訪問該文本文件:

Nginx開啟gzip壓縮演示

此時傳輸資源大小為1.3MB

我們將gzip打開後reload Nginx再次訪問該文本:

Nginx開啟gzip壓縮演示

可見此時傳輸資源大小為12.4KB

說明gzip對文本的壓縮是非常理想的

對比兩次結果從Time第一次為9.09s到第二次50ms可以看出Nginx開啟gzip壓縮大大提高了網頁響應的速度。

鏈接:https://www.jianshu.com/p/67075626774c


分享到:


相關文章: