It dawned on me today that I often use my own personal server for hosting a wide array of image types: screen shots, site/layout images, buttons, affiliate banners, digital camera photos, etc
Specifically I frequently upload screen shots for bugs and error troubleshooting, etc. and often link directly to the image
within forum posts, emails, or blog entries.
So what if I wanted to delete or move the image from the defined location on my server?
Well, since I am running MODx, the file ultimately will not be found and MODx will handle this by serving my custom 404 Error page.
For most, this action is probably desired. If someone is trying to hit my site and the requested URL does not exist, I’d want them to at least access the portion of my site that
does exist.
However, this
also means that for
every user that is viewing the forum post with the old image reference that my site would handle each request via MODx.
This sends a few unnecessary calls to my database, however. The seemingly empty forum post does not benefit either.
Until now.
A little .htaccess magic allows me to serve an "Image Not Found" image whenever an old image reference is requested, bypassing the database entirely:
# Rewrite old image references to an "image not found" image (Prevent calls to the database)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} \.(png|jpg|jpeg|gif|bmp|tif|tiff)$ [NC]
RewriteRule ^(.*)$ assets/images/image_not_found.jpg [L]
If using Friendly URLs, be sure to place the previous code ABOVE this section in your .htaccess file.
# The Friendly URLs part
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
The result:
# Rewrite old image references to an "image not found" image (Prevent calls to the database)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} \.(png|jpg|jpeg|gif|bmp|tif|tiff)$ [NC]
RewriteRule ^(.*)$ assets/images/image_not_found.jpg [L]
# The Friendly URLs part
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
8) Notice how you can handle for various image types:
PNG, JPG, JPEG, GIF, BMP, TIF, TIFF, etc
(Don’t forget to create your image_not_found.jpg image (otherwise, I’d recommend pointing to assets/js/x.gif)! You could even place your URL on the image so those interested can find your site!)