Thursday, February 3, 2011

mod_rewrite rule for images with query string

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>
  • 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>
    
    Swish : I think you might want to change one line to: RewriteCond %{QUERY_STRING} ^.+ so it will match only if a query string is present
    Weboide : Nice catch ;) thanks
    Bryan M. : Excellent! Works great (good to know I was close). I actually used RewriteCond %{QUERY_STRING} ^[wh] to limit the keys accepted, so as not to interfere with any other potential query params down the road.
    From Weboide

0 comments:

Post a Comment