Implement Fast 404s for Static Files

A drawback of dynamic CMS like Drupal is the handling of 404 errors, or Page Not Found errors. Drupal handles every request through index.php. If a file or path does not exist, Drupal has already bootstrapped the entire LAMP and modules stack. 2Bits came up with a solution. Below I show the code I use at the bottom of settings.php. You may need to carefully inspect the code, to see whether it fits to your situation. Find the original discussions via the references below.

Put this code near the bottom of settings.php

// List of extensions for static files
$exts = 'txt|png|gif|jpe?g|shtml?|css|js|ico|swf|flv|cgi|bat|pl|dll|exe|asp|xml';

// It is not an imagecache path, which we allow to go through Drupal
if (!strpos($_SERVER['QUERY_STRING'], 'imagecache')) {
  // It is not our main feed page
  if ($_SERVER['QUERY_STRING'] != 'rss.xml') {
    // Is it a static file? 
    if (preg_match('/\.(' . $exts . ')$/', $_SERVER['QUERY_STRING']))
      // Just send a 404 right now ...
      {
      header('HTTP/1.0 404 Not Found');
      print '';
      print '';
      print '

Not Found

'; print '

The requested URL was not found on this server.

'; print ''; exit(); } } }

Advantages

  • Code goes in settings.php, no core hack
  • Stops Drupal early on 404s
  • Works with imagecache

References