donderdag 9 februari 2012

Responsive images trough .htaccess

Responsive webdesign is the hot the thing right now. However, making images responsive can be a bit more tricky than a simple CSS media query.

Using the following .htaccess you can serve both low and high quality images depending on the useragent by creating 2 different images and placing them in different directories.


<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/images_retailer/.*$
RewriteCond %{HTTP_ACCEPT} "text\/vnd\.wap\.wml|application\/vnd\.wap\.xhtml\+xml" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "e860|u940|ux840|compal|wireless| mobi|ahong|lg380|lgku|lgu900|lg210|lg47|lg920|lg840|lg370|sam-r|mg50|s55|g83|t66|vx400|mk99|d615|d763|el370|sl900|mp500|samu3|samu4|vx10|xda_|samu5|samu6|samu7|samu9|a615|b832|m881|s920|n210|s700|c-810|_h797|mob-x|sk16d|848b|mowser|s580|r800|471x|v120|rim8|c500foma:|160x|x160|480x|x640|t503|w839|i250|sprint|w398samr810|m5252|c7100|mt126|x225|s5330|s820|htil-g1|fly v71|s302|-x113|novarra|k610i|-three|8325rc|8352rc|vx54|c888|nx250|n120|mtk |c5588|s710|t880|c5005|i;458x|p404i|s210|c5100|teleca|s940|c500|s590|foma|samsu|vx8|vx9|a1000|_mms|myx|a700|gu1100|bc831|e300|ems100|me701|me702m-three|sd588|s800|ac831|mw200|brew |d88|htc\/|htc_touch|355x|m50|km100|d736|p-9521|telco|sl74|ktouch|m4u\/|me702|kddi|phone|lg |sonyericsson|240x|x320|vx10|motorola|mmp|wap|o2|pocket|kindle|psp|treo|sony|symbian|vx1000|nokia|lge |m800|samsung|mobile|windows ce|epoc|opera|mini|nitro|j2me|midp-|cldc-|netfront|mot|up\.browser|up\.link|audiovox|blackberry|ericsson,|panasonic|philips|sanyo|sharp|sie-|portalmmm|blazer|avantgo|danger|palm|series60|palmsource|pocketpc|smartphone|rover|ipaq|au-mic,|alcatel|ericy|vodafone\/|wap1\.|wap2\.|iPhone|android|googlebot-mobile" [NC]
RewriteRule ^images/(.*)$ images_retailer/$1 [L,QSA,NC]
</IfModule>
Put the regular image in the "image/" directory and the small version in "images_retailer/".
Now you can use 

<img src="images/car.jpg"/>
To call both images depending on the type of useragent.
Let's hope a more permanent, native, solution will be implented in HTML5 in the near future.



For a demo, check here