在虛擬主機有安裝 SuPHP 情況下啟用 Gzip

Author: Eric  //  Category: Free Teaching

01. 因為希望 WordPress 可以再快一點, 所以就想把 Gzip 打開, 這就是成長的動力, 好還要更好, 沒有最好只有更好, 於是創了個 phpinfo.php, 想更進一步的來了解一下自己的虛擬主機。

<?php phpinfo(); ?>

查看了自己的 Server 是否有支援 GZIP, 發現恰是一切正常.

HTTP_ACCEPT_ENCODING  gzip, deflate
_SERVER["HTTP_ACCEPT_ENCODING"] gzip, deflate
_ENV["HTTP_ACCEPT_ENCODING"] gzip, deflate

02. 於是分別在 .htaccess file 加上

a. 結果出現 HTTP 500 - Internal Server Error.

php_flag zlib.output_compression on
php_value zlib.output_compression_level 4

b. 第二種沒反應 // that is, 不支持 mod_deflate

<ifmodule mod_deflate.c>
DeflateCompressionLevel 4
AddOutputFilterByType DEFLATE text/html text/plain text/xml application/x-httpd-php
AddOutputFilter DEFLATE js css
</ifmodule>

03. 兩種都沒成功, 於是又上網 Google , 找了好久才發現如果主機有裝 SuPHP, 寫法會有不同, 要稍稍修正。

When SuPHP is enabled, it is no longer possible to to include php_value directives in .htaccess files.

Instead of adding these directives to your .htaccess file, add them into a file called php.in and place this file in the same directory that your script runs in. Most often this will be public_html directory, but in some cases you will install your script in a subdirectory. Wherever your script runs, this is the place for your php.ini file. You will need to drop the "php_flag" and "php_value" prefix. You will also need to put an equals (=) sign between the setting and the value.

a. 前面不要加上 "php_flag" and "php_value"
b. 設定和值中間用 "=" 隔開
c. 原本放在 .htaccess file -> 改放置在 php.ini file

eg:原本放 .htaccess file

php_value max_execution_time 60
php_flag zlib.output_compression on

改後放 php.ini // 目錄下沒 php.ini, 就自己創, 改好後再上傳, 非 php.ini.txt 喔

max_execution_time = 60
zlib.output_compression = on

所以原本在 .htaccess file 的寫法, 要改成下面的樣子, 然後放置於 php.ini

zlib.output_compression = on
zlib.output_compression_level = 4

04. 最後, 別忘了來 Gzip Test 驗收成果

ps.
a. 如果啟用 Gzip 出現 HTTP 500 - Internal Server Error, 很可能就是您的虛擬主機有使用 SuPHP
b. JustHost 有使用 SuPHP
c. 沒特別設定 compression level 的話, 預設是6, 數字可以是 1~9
d. Compression test : 32,380 bytes // 超過 4 級就沒什麼差別了

Level 1: 9,161 bytes 71.7%
Level 2: 8,915 bytes 72.5%
Level 3: 8,757 bytes 73.0%
Level 4: 8,400 bytes 74.1%
Level 5: 8,215 bytes 74.6%
Level 6: 8,155 bytes 74.8%
Level 7: 8,120 bytes 74.9%
Level 8: 8,108 bytes 75.0%
Level 9: 8,100 bytes 75.0%

Ref:
01. All servers having SuPHP installed for added security
02. How to use gzip compression on your PHP websites
03. Force GZIP compression on your HostMonster-hosted website
04. GZIP files