5. 压缩传输

目前主要有两个模块可用于输出压缩:mod_gzip 和 mod_gunzip。它们使用不同的方法来实现减少带宽的目标。

mod_gunzip 期望文件系统上有压缩文件,并在浏览器无法处理压缩数据时解压缩它们。好处是 CPU 使用率较低,因为大多数浏览器都能够处理 gzip 压缩的内容。另一方面,当今的大部分内容是动态生成的,例如 PHP,而这些内容将以未压缩的方式传输。

mod_gzip 不需要系统上有压缩文件,所有定义的内容都会在传输前被压缩。好处是可以压缩动态生成的内容,缺点是 CPU 使用率较高,因为每个请求都必须即时压缩。Mod_gzip 可以处理已经压缩的数据,例如 index.html.gz,并按原样发送。

结论:您需要仔细决定哪个模块更适合您。如果您需要为每 GB 传输的数据付费,并且 CPU 性能无关紧要,那么 mod_gzip 是您的选择。如果响应时间很重要(请求和传输之间的延迟),并且您的带宽便宜或无限,那么 mod_gunzip 更符合您的需求。

Martin Kiff 关于 mod_gunzip 的文档可以帮助您做出这个决定,这是一个很好的页面:http://www.innerjoin.org/apache-compression/howto.html

5.1. mod_gzip

5.1.2. 构建和安装

要成功编译 mod_gzip,您需要编辑Makefile并提供 apxs 的正确路径

make
make install

5.1.3. 示例配置

将以下内容放入您的/usr/local/apache/conf/httpd.conf:

示例 5. /usr/local/apache/conf/httpd.conf

mod_gzip_on                 Yes
mod_gzip_can_negotiate      Yes
mod_gzip_dechunk            Yes
mod_gzip_minimum_file_size  600
mod_gzip_maximum_file_size  0
mod_gzip_maximum_inmem_size 100000
mod_gzip_keep_workfiles     No
mod_gzip_temp_dir           /usr/local/apache/gzip
mod_gzip_item_include       file \.html$
mod_gzip_item_include       file \.txt$
mod_gzip_item_include       file \.jsp$
mod_gzip_item_include       file \.php$
mod_gzip_item_include       file \.pl$
mod_gzip_item_include       mime ^text/.*
mod_gzip_item_include       mime ^application/x-httpd-php
mod_gzip_item_include       mime ^httpd/unix-directory$
mod_gzip_item_include       handler ^perl-script$
mod_gzip_item_include       handler ^server-status$
mod_gzip_item_include       handler ^server-info$
mod_gzip_item_exclude       file \.css$
mod_gzip_item_exclude       file \.js$
mod_gzip_item_exclude       mime ^image/.*

您可能希望将压缩结果记录到您的访问日志中。这可以通过更改 LogFormat 指令来完成,在/usr/local/apache/conf/httpd.conf
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" mod_gzip: %{mod_gzip_compression_ratio}npct." combined

5.2. mod_gunzip

5.2.1. 下载源代码

原始站点:http://www.oldach.net/mod_gunzip.tar.gz

5.2.2. 构建和安装

tar -xvzf mod_gunzip.tar.gz
cd mod_gunzip-2

/usr/local/apache/bin/apxs -i -a -c -lz mod_gunzip.c

5.2.3. 示例配置

将以下内容放入您的/usr/local/apache/conf/httpd.conf:

示例 6. /usr/local/apache/conf/httpd.conf

AddType text/html .htmz
AddHandler send-gunzipped .htmz

现在您可以 gzip 压缩您的 html 文件并将它们重命名为例如

gzip index.html
mv index.html.gz index.htmz

当然,您必须将所有链接更改为 htmz,例如 <a href="page.htmz">Some page</a>