My day with mod_rewrite

I’m a big fan of the Image Redirection script at ImgRed.com. It’s a great script to handle one of the most annoying things out there – posting images that are already hosted somewhere on the internet at another host. There’s no need to be ‘that guy’ who leeches bandwidth that isn’t his, and I’ve found that some other free image hosting services can be limited in functionality or tedious to use on their own.

Anyway, the script is something that I had set up at my old site with relatively little effort.  The one thing that continually trips me up on setting it up, though, is making it all nice with Apache’s mod_rewrite functionality, which, for some reason, decided to give me fits on my new server.

Granted, I’m no god of mod_rewrite – setting up regex is hard enough when you can easily see and debug the output!  On my old site, I started out with what the programmer of ImgRed had provided me, which worked flawlessly on it:

RewriteEngine On
RewriteRule ^(http://.*)$ http://site.com/ImgRed.php?Image=$1 [L]

The ultimate goal was to clean up the URLs and make them sane – the same functionality of ImgRed.com that lets you prepend any image URL with its domain and have it all ‘just work’. This was no problem on the old server, running a dated but patched installation of CentOS 3. My current server, running Ubuntu 8.04 LTS, wasn’t playing nicely with it – it kept returning 404 errors. I ended up having to create a script just to output what URL string was getting captured and passed in as the substring to the script, and discovered that for reasons I have not been able to figure out, it was stripping one of the two forward slashes in ‘http://’ from the URL, rendering it invalid.

I finally managed to get it to work with the following:

RewriteEngine On
RewriteRule ^http:(.*)$ ImgRed.php?Image=http:/$1 [L]

Basically, I just cut the substring down to what it consistently outputs as the second slash in the ‘http://’, and everything following it – and then manually prepended it to the URL. I don’t think the script will exactly play with HTTPS or FTP URLs anyway.

Tags: , , , ,

Leave a Reply

You must be logged in to post a comment.