什么是Gzip压缩?

  • Gzip是一种压缩文件(使其更小)的方法,用于更快的网络传输。
  • 它也是一种文件格式。压缩允许您的Web服务器提供更小的文件大小,使您的网站用户加载更快。

启用gzip压缩是一种标准做法。 如果您出于某种原因不使用它,您的网页可能比竞争对手慢。

如何启用Gzip压缩

  • 通过webserver配置启用压缩
  • 不同的网络服务器有不同的指令(下面说明)

以下是启用压缩的最常见方法,包括.htaccess,Apache,Nginx和Litespeed网络服务器。

以下代码应添加到您的.htaccess文件中…

<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>

在Apache网络服务器上启用压缩

上面的指令和代码将在Apache上工作。 如果它们不工作,有另一种方式,可能为你工作。 如果上述代码似乎无法正常工作,请将其从.htaccess文件中删除,然后尝试使用此代码:

AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript

在NGINX Web服务器上启用压缩

要在NGINX中启用压缩,您需要将以下代码添加到您的配置文件中

gzip on;
gzip_comp_level 2;
gzip_http_version 1.0;
gzip_proxied any;
gzip_min_length 1100;
gzip_buffers 16 8k;
gzip_types text/plain text/html text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript;

# Disable for IE < 6 because there are some known problems
gzip_disable "MSIE [1-6].(?!.*SV1)";

# Add a vary header for downstream proxies to avoid sending cached gzipped files to IE6
gzip_vary on;

测试压缩

https://varvy.com/tools/gzip/

https://varvy.com/pagespeed/

参考:https://varvy.com/pagespeed/enable-compression.html