[php]關於 apache 的gzip和no-gzip

   


[php]關於 apache 的gzip和no-gzip

關鍵字:資料傳輸 xml

source code:
@apache_setenv('no-gzip', 1);

1. apache_setenv() : 是php內件用來設定apache內參數的function
 說明:
  bool apache_setenv ( string $variable , string $value [, bool $walk_to_top = false ] )
* Set an Apache subprocess_env variable
*parameter – variable: The environment variable that's being set.
*parameter – value : The new variable value.
*parameter – walk_to _top: Whether to set the top-level variable available to all Apache layers.
*return value: Returns TRUE on success or FALSE on failure.
* apache_setenv() sets the value of the Apache environment variable specified by variable.
Note:
When setting an Apache environment variable, the corresponding $_SERVER variable is not changed.
[Example]
       Example #1 Setting an Apache environment variable using apache_setenv()
<?php
apache_setenv("EXAMPLE_VAR""Example Value");
?>

2. gzip: 是apache內部參數,用途說明如下:[以下轉自Tony Blog

  Apache 伺服器在第 2 版之後,內建了 Gzip 的壓縮傳輸功能
  
預設 :未開啟
  
功能:
   對指定檔案,像是 html、css 等,在壓縮之後才傳輸,可以讓傳輸的流量變小,
   速度也會加快。
   如果要傳輸的檔案很大,開啟 Gzip 壓縮傳輸將會很明顯的得到速度的提升。
  
觀察方法:
   透過開發者工具觀察傳輸容量
  
如何知道檔案有使用 Gzip 壓縮傳輸:
   在檔頭中如果有出現 Content-Encoding: "gzip",如下圖:  
   就表示這個檔案是經過 gzip 壓縮後傳輸的。
  
可以看看你使用的瀏覽器支援何種壓縮:
     

啟用方法:

一、編輯http.conf (/etc/httpd/conf/httpd.conf)

檢查 LoadModule deflate_module modules/mod_deflate.so 是否存在,若無,請自行加入

vim 操作提示,輸入 / 可以查詢,

所以接著輸入 LoadModule或mod_deflate。

如果前面有加 # 字號,那是註解,把它刪掉來啟用。

二、建立deflate.conf (/etc/httpd/conf.d/deflate.conf)

內容:
  1. #Set to gzip all output
  2. SetOutputFilter DEFLATE
  3. #AddOutputFilterByType DEFLATE text/html text/css text/plain text/xml application/x-javascript application/x-httpd-php
  4. #exclude the following file types
  5. SetEnvIfNoCase Request_URI \.(?:exe|t?gz|zip|iso|tar|bz2|sit|rar|png|jpg|gif|jpeg|flv|swf|mp3)$ no-gzip dont-vary
  6. #set compression level
  7. DeflateCompressionLevel 6
  8. #Handle browser specific compression requirements
  9. BrowserMatch ^Mozilla/4 gzip-only-text/html
  10. BrowserMatch ^Mozilla/4.0[678] no-gzip
  11. BrowserMatch bMSIE !no-gzip !gzip-only-text/html
  12. SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0

說明:

SetOutputFilter DEFLATE 這行會把所有要輸出的檔案都壓縮,

你可以用 AddOutputFilterByType DEFLATE 後面加上指定的 MIME 類型的檔案,來指定只壓縮某些類型的檔案(這裡註解掉不使用)。

我們指定所有輸出的檔案都要壓縮,但其實有些檔案執行壓縮的效率不高,所以要排除,避免耗用太多 CPU,

使用 SetEnvIfNoCase Request_URI 來把這些類型的檔案排除。

接著設定壓縮等級,等級從 1 到 9 級,數字越高,壓縮率越高,但 CPU 耗用的也越大,可以自行調整,
預設是 6,不建議設太高,除非你伺服器的 CPU 閒閒沒事做。

最後就是針對瀏覽器做個別調整。

記得要重新啟動 Apache 伺服器:service httpd restart

也可以單獨在 .htaccess 檔中設定。
如果是使用 Nginx 伺服器,在官方網站也有說明如何啟用:Module ngx_http_gzip_module

完成後,可以在 Check HTTP Compression 這個網站測試看看效能如何。

留言

熱門文章