1、php方式開啟
原理:
header("Content-Encoding: gzip"); echo gzencode('songjiankang');
示例1:
function ob_gzip ($content) // $content 就是要壓縮的頁面內容,或者說餅干原料 { if (! headers_sent() && // 如果頁面頭部信息還沒有輸出 extension_loaded("zlib") && // 而且zlib擴展已經加載到PHP中 strstr($_SERVER["HTTP_ACCEPT_ENCODING"], "gzip")) // 而且瀏覽器說它可以接受GZIP的頁面 { $content = gzencode($content . " \n//此頁已壓縮", 9); // 此頁已壓縮”的注釋標簽,然后用zlib提供的gzencode()函數執行級別為9的壓縮,這個參數值范圍是0-9,0表示無壓縮,9表示最大壓縮,當然壓縮程度越高越費CPU。 // 然后用header()函數給瀏覽器發送一些頭部信息,告訴瀏覽器這個頁面已經用GZIP壓縮過了! header("Content-Encoding: gzip"); header("Vary: Accept-Encoding"); header("Content-Length: " . strlen($content)); } return $content; // 返回壓縮的內容,或者說把壓縮好的餅干送回工作台。 } ob_start('ob_gzip');
示例2:
#ob_gzhandler 為php內置函數,具體參考手冊 ob_start('ob_gzhandler');
2、apache的方式開啟:
a.開啟模塊:
LoadModule deflate_module modules/mod_deflate.so
LoadModule headers_module modules/mod_headers.so
b.httpd.conf中增加
<ifmodule deflate_module> DeflateCompressionLevel 9 AddOutputFilterByType DEFLATE text/html text/plain text/xml application/json application/xml AddOutputFilter DEFLATE js css AddOutputFilter INCLUDES .shtml .htm .xml .php .html </ifmodule>
c.重啟服務器