GZip files with .htaccess and PHP that works with WordPress

codeLately, I have been burning through bandwidth. I had thought that I have enabled all possible tweaks until I discovered that there is an additional work-a-round that will use gzip compression for PHP, CSS, and JS files.

While there are more simplified solutions for use, WordPress installations create additional obstacles that this code addresses well. The results may be measured using YSlow a plugin for Firefox or Rex Swain’s HTTP Viewer. In my case, the file sizes were reduced by half for most pages.

I had tried several possible suggestions posted throughout the internet community until I found a solution that actually worked for me. For WordPress installations this solution works great as there are CSS and JS files throughout the installation.

Create a file called gzip.php and put in the root folder where WordPress is installed.

<?php
if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) && substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start('ob_gzhandler');
else ob_start();
?>

Then append to .htaccess

################## GZip Files ###################
<filesmatch "\.js$"="">
AddHandler application/x-httpd-php .js
php_value default_mimetype "text/javascript"
</filesmatch>
<filesmatch "\.css$"="">
AddHandler application/x-httpd-php .css
php_value default_mimetype "text/css"
</filesmatch>
<filesmatch "\.(htm|html|shtml)$"="">
AddHandler application/x-httpd-php .html
php_value default_mimetype "text/html"
</filesmatch>
php_value auto_prepend_file /absolute/path/to/gzip.php

1 Comment

Comments are closed.