Submit Tips/Quickies

Application Architecture : Optimization

Serving pre-compressed (gz) files using PHP and a small Rewr

Submitted By: Daniel Frechette
Date: 04/18/06 16:18

Here is my solution for returning precompressed (.gz) files when available:


==== File .htaccess ====


Options +FollowSymlinks
AddType text/x-component .htc
# Redirect requests for css, htc, js and xsl files to a php script
# that will return precompressed (.gz) files when available.
RewriteEngine On
RewriteRule (.*.css|.*.htc|.*.js|.*.xsl) fetchGz.php?f=$1 [NC]


==== File fetchGz.php ====


<?php
/*
** Written by Daniel Frechette, April 2006
** Return a precompressed (.gz) file if available for file
** extensions css, htc, js and xsl.
*/
error_reporting(0); // Turn off all error reporting
$fileName = $_GET["f"];
$contentType = "";
$extArray = explode(".", $fileName);
if (($last = count($extArray) - 1) != 0) {
   switch ($extArray[$last]) {
      case "css":
         $contentType = "text/css";
         break;
      case "htc":
         $contentType = "text/x-component";
         break;
      case "js":
         $contentType = "text/javascript";
         break;
      case "xsl":
         $contentType = "text/xml";
         break;
   }
}
$gzFileName = $fileName.".gz";
if (eregi("gzip",$_SERVER["HTTP_ACCEPT_ENCODING"]) && file_exists($gzFileName)) {
   header("Content-Type: ".$contentType."; charset=UTF-8");
   header("Content-Encoding: gzip");
   header("Content-Length: ".filesize($gzFileName));
   header("File-Name: ".$gzFileName); // Custom header
   readfile($gzFileName);
}
else {
   header("Content-Type: ".$contentType."; charset=UTF-8");
   header("File-Name: ".$fileName); // Custom header
   readfile($fileName);
}
die;
?>


==== Usage example ====


<?xml version="1.0" ...?>
<!DOCTYPE html ...>
<html ...>
<head>
   <style type="text/css">
      @import url(./styles/foo.css);
   </style>
   <script type="text/javascript" src="./scripts/bar.js"></script>
</head>
<body>
   ...
</body>
</html>


How it works

The rewrite rule automatically forwards requests for files foo.css and bar.js to fetchGz.php. The PHP script will check if gzip versions of the files exist (i.e. foo.css.gz and bar.js.gz). If found, it will return the gz versions. Otherwise, it will return the requested file (uncompressed version).

To check if the process works properly, I added a custom header tag called File-Name to indicate which file was returned by the script..

This process is VERY FAST and serves my web files at lightning speed.

Regards,

Daniel


Comments:

No Messages Found

You can post questions/corrections/feedback here

 

If you are looking for help, please post on the appropriate forum here. Your questions will be answered much more quickly.

Add A Comment:

Name:

Email:

Subject:

Message:

To reduce spam posts, messages are now manually approved

You are not [logged in]. That means your account will not get credit for this post.