通过mod_deflate进行HTTP文本压缩

来源:互联网 发布:最好的监控软件 编辑:程序博客网 时间:2024/06/05 14:39

mod_deflate简介:
mod_deflate模块提供了DEFLATE输出过滤器,允许服务器在将输出内容发送到客户端以前进行压缩,以节约带宽。

中文参考手册:
http://www.phpchina.com/manual/apache/mod/mod_deflate.html
配置过程:
仅针对于apache2.0及以上服务器,apache1.x版本并不是使用mod_deflate进行压缩。
编辑/etc/apache2下的httpd.conf文件(apache服务器的配置文件)
mac下的修改方法:
打开终端,输入sudo /Applications/TextEdit.app/Contents/MacOS/TextEdit /etc/apache2/httpd.conf
对于文件的改动:
1、去掉语句
LoadModule deflate_module libexec/apache2/mod_deflate.so  以及
LoadModule headers_module libexec/apache2/mod_headers.so
前面的注释,如果没有,则添加进去Dynamic Shared Object (DSO) Support后面的一堆加载模块中
2、增加语句
如果只针对与文本的压缩,那么增加一句:

AddOutputFilterByType DEFLATE text/html text/plain text/xml

便可。下面的语句的作用是在传输时压缩除了图片文件以外的所有格式

<Location "/">
# Insert filter
SetOutputFilter DEFLATE
# Netscape 4.x has some problems...
BrowserMatch ^Mozilla/4 gzip-only-text/html
# Netscape 4.06-4.08 have some more problems
BrowserMatch ^Mozilla/4/.0[678] no-gzip
# MSIE masquerades as Netscape, but it is fine
# BrowserMatch /bMSIE !no-gzip !gzip-only-text/html
# NOTE: Due to a bug in mod_setenvif up to Apache 2.0.48
# the above regex won't work. You can use the following
# workaround to get the desired effect:
BrowserMatch /bMSI[E] !no-gzip !gzip-only-text/html
# Don't compress images
SetEnvIfNoCase Request_URI /
/.(?:gif|jpe?g|png)$ no-gzip dont-vary
# Make sure proxies don't deliver the wrong content
Header append Vary User-Agent env=!dont-vary
</Location>
其注释的中文版本如下(Mac下本来编码版本是original Western (Mac OS Roman) encoding,中文需要使用其他编码如UTF-8)
<Location />
# 插入过滤器
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
</Location>
具体的语句解释在中文手册里。
3、保存,重启服务器
压缩测试:
可以在file:///var/log/apache2/access_log中查看压缩效果。
我写了一个测试网页,里面不断复制粘贴“这是一个测试网页”,得到大小为154K的文件
在本地服务器调用后,查看log,得到在开启压缩前:
192.168.1.138 - - [30/Jun/2011:12:18:43 +0800] "GET /main.html HTTP/1.1" 200 157892
可见网页是全部下载,大小157892byte,在开启压缩后,得到
192.168.1.138 - - [30/Jun/2011:12:19:48 +0800] "GET /main.html HTTP/1.1" 200 1182
可见压缩成功,且效果可观