PNG to GIF URL rewriting in Apache

Q I am writing a website that uses .png images throughout - most of these images use transparency. It works great on all the latest browsers but (as expected) not IE6. To compensate for this I've created .gif versions of each of the graphics (as well as a custom style sheet) which should load in place of the .png images if the user is still on IE6. To achieve this I want to use mod_rewrite and .htaccess to make it transparent - so that images/png/image1.png is rewritten as images/gif/image1.gif. This is my .htaccess file

RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} "MSIE 6"
RewriteRule /images/png/([A-Za-z0-9])+\.png$ /
RewriteCond %{HTTP_USER_AGENT} "MSIE 6"
RewriteRule css/style.css css/iestyle.css

The CSS rewrite works perfectly but the image replacement (png to gif) doesn't.

A You have the right idea in using mod_rewrite to change the URLs. It is falling over because you are using a + to join strings, but mod_rewrite works with regular expressions, where + is a pattern matching character, not an operator. With regular expressions, you don't need to join strings, instead you use parentheses to mark the parts you want unchanged and $1, $2... to include them in the destination, as you have done, and everything is either text or regular expression characters. So to replace the last occurrence of foo in a string with bar, you would use


In your case, you want to change anything starting with images/png and ending in .png, replacing both occurrences of png with gif. You can do this by replacing your first RewriteRule line with one of

RewriteRule /images/png/(.*)\.png$ /images/gif/$1\.gif
RewriteRule /(.*)/png/(.*)\.png$ /$1/gif/$2\.gif

The first is easier to read, but the second will work with images in other directories too.

Follow us on or Twitter

Username:   Password: