先說下好處:文本頁面(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模塊來確保不會發送錯誤的內容。
<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>
另有一種簡單的設置:
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%。
參考文檔:
Apache模塊 mod_deflate
http://www.itlearner.com/code/apache2.2/mod/mod_deflate.html
Apache deflate模塊配置說明
http://www.itlearner.com/article/2007/3819.shtml