mod_deflate在Web服务器层进行压缩控制,因此不需要通过修改程序代码就可以达到减小传输文件大小的功能。但是对于特别大的文件,在压缩的时候需要花费一定的时间,因此下载的人会在一段时间内无法得到响应。

查看了Apache的配置:

Apache配置代码:


<ifmodule mod_deflate.so>
DeflateCompressionLevel 9
SetOutputFilter DEFLATE
#DeflateFilterNote Input instream
#DeflateFilterNote Output outstream
#DeflateFilterNote Ratio ratio
#LogFormat '"%r" %{outstream}n/%{instream}n (%{ratio}n%%)' deflate
#CustomLog logs/deflate_log.log deflate
</ifmodule>

修改为:

Apache配置代码:


<IfModule mod_deflate.so>
DeflateCompressionLevel 6
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/atom_xml
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE application/x-httpd-php
AddOutputFilterByType DEFLATE p_w_picpath/svg+xml
#DeflateFilterNote Input instream
#DeflateFilterNote Output outstream
#DeflateFilterNote Ratio ratio
#LogFormat '"%r" %{outstream}n/%{instream}n (%{ratio}n%%)' deflate
#CustomLog logs/deflate_log.log deflate
</ifmodule>

Apache2中的实时压缩解压的模块编译在mod_deflate模块中,替换了原来的mod_gzip模块。

编译apache的时候 –enable-deflate 这个参数是默认开启的,编译完会有mod_deflate模块。

配置站点:

如果我们想使一个文件传输的时候进行加密,我们在站点配置文件里增加这样的配置

<Location />
SetOutputFilter DEFLATE
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
SetEnvIfNoCase Request_URI \
\.(?:gif|jpe?g|png)$ no-gzip dont-vary
Header append Vary User-Agent env=!dont-vary
</Location>
这样,/var/www/htdocs目录下的所有mime类型为text/html的文件就可以启用

未压缩的http头:

Date Fri, 21 Oct 2011 05:43:36 GMT
Server Apache/2.2.16 (Unix) DAV/2
Last-Modified Fri, 21 Oct 2011 05:42:23 GMT
Etag "48d46c6-12853-4afc8898ecdc0"
Accept-Ranges bytes
Content-Length 75859
Content-Type text/html
Vary Accept-Encoding,User-Agent


压缩后的http头:

Date Fri, 21 Oct 2011 05:43:36 GMT
Server Apache/2.2.16 (Unix) DAV/2
Last-Modified Fri, 21 Oct 2011 05:42:23 GMT
Etag "48d46c6-12853-4afc8898ecdc0"
Accept-Ranges bytes
Vary Accept-Encoding,User-Agent
Content-Encoding gzip
Content-Length 18323
X-UA-Compatible IE=EmulateIE7
Content-Type text/html


原来length为75859,压缩后为18323,效果还是很明显的。

不过对于length很小的文件,是不进行压缩的。