My host, 1&1, claims to allow gzip compression through Apache. However, when I try to set it up along with etags and expires it doesn’t seem to work. I devised this fancy script to add cache-control and etag headers to js, css, and xml files.
First, you must create a php file with the following code and upload it to your root directory (you can actually upload it anywhere, but the root is easiest). I named the file expire.php.
$pathinfo = pathinfo($_ENV['SCRIPT_FILENAME']);
$extension = $pathinfo['extension'];
header('Content-type: text/css; charset=utf-8');
header('Content-type: application/xml; charset=utf-8');
$max_age = 300 * 24 * 60 * 60; // 300 days
$expires = time() + $max_age;
header( "Expires: " . date( "r", $expires ) );
$etag = dechex( getlastmod() );
header( "ETag: " . $etag );
$cache_control = "must-revalidate, proxy-revalidate, max-age=" . $max_age . ", s-maxage=" . $max_age;
header( "Cache-Control: " . $cache_control );
Basically what is happening is the script first sets the correct content-type then calculates the expire date, sets the ETag, and finally sets the Cache-Control. What we need to do next is make sure this script prepends all php scripts. This is done by modifying php.ini.
If you have access to the root php.ini file you may modify that, however I do not so I simply created a new one and place it in my root directly. The php.ini file will be loaded for any php script in that directory or sub directories. Here is the code to place in php.ini
Very important: You must change DOCUMENT_ROOT to the actual document root of your expire.php file. To get this use
and search for “DOCUMENT_ROOT”. The output-handler line is how to get gzip compression on your files.
Now, for the final step, modifying .htaccess to run js, css, and xml files as php. Just add the following to your .htaccess file.
RemoveHandler .css .js .xml
AddType x-mapp-php5 .php .shtml .html .htm .txt .js .css .xml
And done, your files should now be gzip compressed and have expires headers.