Rotating images with HTTP redirects


One day while surfing the web, I started looking at all the sites that had adds, specifically rotating adds. So, with my curiosity piqued, I started looking at how the rotating adds worked. What I found disturbed me. In short, many of the add rotation methods relied on state being stored on the server. As a unix admin, this meant that every page load was writing to a file on the server, not a good idea. This this stuck in my craw, I started pondering. (Me pondering things is both good and bad, if not down rite dangerous.) However, in this case, my pondering turned out to be a good thing. Specifically, I decided that state was not required for add rotation. All that was required is some form of random process, and a way to direct the browser to act on the random data. Of course, based on my personal bias, JavaScript (or any other client side method) is out.

Fortunately, Apache the venerable HTTP server that it is, had an easy solution for the random portion. Specifically, RewriteMap's "rnd" map. RewriteMap's rnd map simply performs a random look up in the specified map file, and returns the result. So, I used the random RewriteMap in conjunction with 302 HTTP redirect to cause requests for a specific (phony) URI to cause Apache to return a 302 HTTP redirect to a random image. Thus, when the browser GETs the image source from the specific (phony) URI, it's given a 302 HTTP redirect to the real image URI. The browser then chases the real image URI and uses it as the source for the image to be displayed. Thus, we have random (rotating) images with out needing to store any state on the server.

Here's how I have Apache configured:

Add the following line's to your Apache httpd.conf file, likely inside of a <VirtualHost...> section.

RewriteEngine      on
RewriteMap         myRandomMap         rnd:/path/to/myMapFile
RewriteRule        ^path/to/specific/phony/URI$       http://%{SERVER_NAME}/path/to/real/image/${myRandomMap:mapKey}         [R=303,L]

Create the myMapFile with the following contents.

mapKey         image1.png|image2.png|image3.png

Update your <img src="..."> to use the "/path/to/specific/phony/URI" from the httpd.conf file.

<img src="/path/to/specific/phone/URI" />

Now you can enjoy your own stateless rotating images using http redirects too.