gzip压缩是在服务器端对体育进行压缩,再由客户端(如浏览器)进行解压的过程。启用gzip压缩不仅可以节省网络传输的带宽,还可以提高应用程序加载的速度,但是会消耗服务器端一定的CPU资源。下图是一个典型的HTTP请求和响应的流程,可以看出,一个原始大小为100K的html文件,经过gzip压缩后只有10KB。
启用压缩前:
启用压缩后:
Apache和Nginx是两种在Linux乐鱼全站app下载上使用广泛的Web服务器,下面就介绍如在两种Web服务器上启用gzip压缩。
Apache
在Apache的配置文件里添加如下代码块:
<IfModule mod_deflate.c>
# compress html, css, javascript, text, xml and fonts
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/x-font
AddOutputFilterByType DEFLATE application/x-font-opentype
AddOutputFilterByType DEFLATE application/x-font-otf
AddOutputFilterByType DEFLATE application/x-font-truetype
AddOutputFilterByType DEFLATE application/x-font-ttf
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE font/opentype
AddOutputFilterByType DEFLATE font/otf
AddOutputFilterByType DEFLATE font/ttf
AddOutputFilterByType DEFLATE image/svg+xml
AddOutputFilterByType DEFLATE image/x-icon
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/xml
# you can also compress by file type/extension:
<files *.html>
SetOutputFilter DEFLATE
</files>
</IfModule>
Nginx
对于Nginx服务器,gzip是默认开启的,可以通过查看Nginx的配置文件来确认这一点。
##
# Gzip Settings
##
gzip on;
gzip_disable "msie6";
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;