Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom etag generation

Tags:

nginx

apache2

How can I configure an apache or nginx server to send Etag headers using an algorithm of my choosing (i.e. not involving inode, mtime or size)? Is there any alternative to compiling a new C module?

like image 381
OrangeDog Avatar asked Aug 10 '11 11:08

OrangeDog


1 Answers

In Apache, ETags are handled as a core feature. The ETag is computed as a hash of several values. You can use the FileETag directive in your httpd.conf or .htaccess file to define conditional behavior for which values to include in the hash, but as you pointed out, your options are limited to:

  • INode - your file's i-node number on the particular server it's served from
  • MTime - the timestamp (in millis) of the server your file is served from
  • Size - the size of your file in bytes
  • All - all of the above
  • None - none of the above

If you want truly custom ETag generation, you would definitely be best off writing an Apache module. However if you need a quick-and-dirty fix, you can generate your own tags by routing your requests to a PHP script and appending the Etag header in the script. The route might look like this in your httpd.conf or .htaccess file:

RewriteCond %{REQUEST_FILENAME} \.png$     # This example looks for .png requests
RewriteRule ^(.*)$ /gentag.php?path=$1 [B] # ...and routes them to a PHP script

The PHP script might look like this:

<?
    $path = $_GET['path'];  // Grab the filepath from GET params
    $cont = file_get_contents($path);  // Get file contents to hash
    $hash = crc32($cont);   // Create your own ETag hash however you like
    header("Etag: $hash");  // Send the custom Etag header
    echo $cont;             // Dump the file contents to output
?>
like image 132
pieman72 Avatar answered Sep 23 '22 02:09

pieman72