标题:Apache2下的网站如何启用Gzip(Deflate)压缩 出处:沧海一粟 时间:Thu, 30 Apr 2009 08:19:43 +0000 作者:jed 地址:http://www.dzhope.com/post/602/ 内容: 先说下好处:文本页面(htm/css/js等)启用压缩后,一般可以压缩70%左右。即50K的文件,实际只需传输15K到客户端,由客户端解压显示。 另外,实践证明,启用Gzip压缩后,不会对搜索引擎收录有影响。 在Apache1.3时代,有一个mod_gzip的模块,但Apache2.x系列已经内置了Deflate模块,因此,只需要安装Deflate模块即可。 一般默认没有装Deflate,最直接的方法就是重装Apache,在原来的配置文件后加上 --enable-deflate --enable-headers 。 如果不想重装,就单独编译,mod_deflate.c在源文件目录的modules/filters下,mod_hearders.c则在modules/metadata目录下。如果用apxs -i -a -c的方法不行,请参考下面的办法,以安装mod_headers为例。 cd modules/metadata/ apxs -i -a -c mod_headers.c Warning! dlname not found in /usr/local/apache2.2.0/modules/mod_headers.la. Assuming installing a .so rather than a libtool archive. chmod 755 /usr/local/apache2.2.0/modules/mod_headers.so chmod: 无法访问‘/usr/local/apache2.2.0/modules/mod_headers.so’: 没有那个文件或目录 apxs:Error: Command failed with rc=65536 参照http://www.9enjoy.com/post/215/的说明, gcc -shared -o mod_headers.so mod_headers.o cp mod_headers.so /usr/local/apache2.2.0/modules /usr/local/apache2.2.0/bin/apxs -i -a -c mod_headers.c Warning! dlname not found in /usr/local/apache2.2.0/modules/mod_headers.la. Assuming installing a .so rather than a libtool archive. chmod 755 /usr/local/apache2.2.0/modules/mod_headers.so [activating module `headers' in /usr/local/apache2.2.0/conf/httpd.conf] 安装成功了。 另网上有一种方法,我还没试过: 编辑apache2安装目录/bin/apr-config(我的机子看了下应该是apr-1-config)文件修改其中的 LDFLAGS 值为 "-lz",然后再重新编译。 装完后,其在conf/httpd.conf中加了如下两句: LoadModule deflate_module modules/mod_deflate.so LoadModule headers_module modules/mod_headers.so 其实安装deflate时mod_headers并不是必须,那为什么要安装呢?主要是其官方配置文件中使用了header模块来确保不会发送错误的内容。 # 插入过滤器 SetOutputFilter DEFLATE # Netscape 4.x 有一些问题... BrowserMatch ^Mozilla/4 gzip-only-text/html # Netscape 4.06-4.08 有更多的问题 BrowserMatch ^Mozilla/4\.0[678] no-gzip # MSIE 会伪装成 Netscape ,但是事实上它没有问题 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 另有一种简单的设置: AddOutputFilterByType DEFLATE text/html text/plain text/xml application/x-httpd-php AddOutputFilter DEFLATE css js 很好理解,可以放在Directory,Virtualhost,Location任意地方。 怎么看是否生效了呢?来记录下日志: #声明输入流的byte数量 DeflateFilterNote Input instream #声明输出流的byte数量 DeflateFilterNote Output outstream #声明压缩的百分比 DeflateFilterNote Ratio ratio #声明日志类型 LogFormat '"%r" %{outstream}n/%{instream}n (%{ratio}n%%)' deflate CustomLog logs/deflate_log deflate 大部分CSS,htm页面都可以压缩到30%,即文章开头我提到的能压缩70%。 Generated by Bo-blog 2.1.1 Release