Mod_rewrite rule for images with query string

.htaccessmod-rewriteregexrewrite

I'm a mod_rewrite novice and a regex noob, but here's what I want to do:

I've got a script that will re-size images on the fly. I'd like to be able to take any image file path, add a query string to it, and have it automatically sent to the script to process.

So something like:

from: http://mysite.com/images/logo.jpg?w=100&h=50 
to:   http://mysite.com/images/thumbs/phpThumb.php?src=logo.jpg&w=100&h=50

Of course, if no query string is specified, it should just point to the original file.

Using the .htaccess file in the /images, I've got this. But it doesn't work at all. Or at best, it break all my sites images:

 <IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{QUERY_STRING} ^.*
    RewriteRule ([^\s]+(\.(?i)(jpg|png|gif|bmp))$) /thumbs/phpThumb.php?src=$1 [L,QSA]
 </IfModule>

Best Answer

First add a RewriteBase, this will strip the /images/ part in the query string. You will get photo.jpg?w=... instead of /images/photo.jpg?w=....

Second add /images/ to the redirection, because your current redirection tells to go to http://mysite.com/thumbs/phpThumbs... instead of http://mysite.com/images/thumbs/phpThumbs....

This gives something like this:

 <IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteBase /images/
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{QUERY_STRING} ^.+
    RewriteRule ([^\s]+(\.(?i)(jpg|png|gif|bmp))$) /images/thumbs/phpThumb.php?src=$1 [L,QSA]
 </IfModule>
Related Topic