How to get rid of 404 errors for favicons and apple-touch-icons

I’ve been seeing a lot of 404 (“page not found”) errors in my Drupal sites’ error logs recently for favicon.ico and apple-touch-icon-precomposed.png (and apple-touch-icon-144x144-precomposed.png, etc.). A quick addition to my .htaccess file fixed it:

<IfModule mod_rewrite.c>
  RewriteEngine on

  # Fix 404s for favicons and touch icons.
  RewriteRule ^(favicon\.ico|apple-touch-icon.*\.png)$ path/to/icons/$1
</IfModule>

No more 404s in my error logs! I use Drupal, so my actual RewriteRule looked more like:

RewriteRule ^(favicon\.ico|apple-touch-icon.*\.png)$ sites/all/themes/mytheme/$1

Drupal users: Note that this is a much better option than creating a hook_menu() item that serves up the favicon from wherever it’s located, as that requires an entire Drupal bootstrap, resulting in increased server load and slow favicon load times. A simple .htaccess RewriteRule does the trick!