Apache和Nginx上的Gzip压缩

・3 分钟阅读

介绍

在传输内容之前压缩内容不仅节省带宽,而且使网络应用程序更快,Web服务器压缩数据和浏览器解压缩所花费的总时间,小于通过网络发送未压缩的数据。本文向你展示了如何使用gzip压缩配置Apache和nginx。

Apache

将以下代码段添加到apache2.conf.htaccess文件。


<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 ,如果没有,打开它的配置文件(sudo nano/etc/nginx/nginx.conf ),并且确保gzip节下的设置未被注释(在下面的代码段中)。


##
# 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;

作者:拉米·阿达博尼亚

Zuoxiaojuan profile image