Using url rewrite engine to serve default avatar to avoid checking for file in PHP

One of the great features of Apache is URL Rewrite. It has helped me to do so many different tasks that I had to blog about this and share the love. One of the things I used it for recently was to provide a solution for a simple problem which was being checked at PHP level.

Problem: Check an avatar file for user, if it exists on file system, use it, else show them a default avatar image.

Solution 1: edit all of the php files which does anything with avatars to put that check in. Not the best way to go and easily forgotten if new piece of code is put in which may cause showing broken images on the site. Therefore solution 2 is more appropriate.

Solution 2(preferred): Use Apache URL Rewriterule feature to take care of this issue. Put .htaccess file in the directory where your avatars are with following content:

RewriteEngine On
RewriteBase /images/avatars/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . /images/avatars/default.gif [L]

Lets look at this line at a time.

First line turns the Rewrite engine on just in case if it wasn’t turned on already.
Second line sets the base to the directory where we are going to be working in.
Third line is where we check to see if the file requested exists or not (! negates -f which is is file?)
Fourth line is where it redirects you to default avatar if requested avatar doesn’t exist.

There you go. Quick, robust, non-code solution. URL Rewrite engine is VERY powerful. What I showed here barely scratches the surface of all the features URL Rewrite engine has to offer. Apache software foundation does a great job providing documentation and numerous examples you may want to look at. The URL Rewriting Guide is one of the resources there.

2 thoughts on “Using url rewrite engine to serve default avatar to avoid checking for file in PHP

Leave a Reply

Your email address will not be published. Required fields are marked *