.Htaccess Forwarding Based on Browser Version
Story by Ben Shambaugh
Many advanced AJAX websites use JavaScript to determine if an user is coming from a mobile phone or a full browser. While this is one way to do it, there are better and faster ways.
The .htaccess file defines custom rules per site “folder”. This means you can set a .htaccess file in any subfolder and have it only apply to the folders and files within it, ignoring all others.
.htaccess is widely used to provide user authorization to parts of websites, but it can do many other things from clean up urls to redirect users based on their version.
Code Snippet:
" RewriteEngine On RewriteCond %{HTTP_USER_AGENT} "acs|alav|alca|amoi|audi|aste|avan|benq|bird|blac|blaz|brew|cell|cldc|cmd-" [NC,OR] RewriteCond %{HTTP_USER_AGENT} "dang|doco|eric|hipt|inno|ipaq|java|jigs|kddi|keji|leno|lg-c|lg-d|lg-g|lge-" [NC,OR] RewriteCond %{HTTP_USER_AGENT} "maui|maxo|midp|mits|mmef|mobi|mot-|moto|mwbp|nec-|newt|noki|opwv" [NC,OR] RewriteCond %{HTTP_USER_AGENT} "palm|pana|pant|pdxg|phil|play|pluc|port|prox|qtek|qwap|sage|sams|sany" [NC,OR] RewriteCond %{HTTP_USER_AGENT} "sch-|sec-|send|seri|sgh-|shar|sie-|siem|smal|smar|sony|sph-|symb|t-mo" [NC,OR] RewriteCond %{HTTP_USER_AGENT} "teli|tim-|tosh|tsm-|upg1|upsi|vk-v|voda|w3cs|wap-|wapa|wapi" [NC,OR] RewriteCond %{HTTP_USER_AGENT} "wapp|wapr|webc|winw|winw|xda|xda-" [NC,OR] RewriteCond %{HTTP_USER_AGENT} "up.browser|up.link|windowssce|iemobile|mini|mmp" [NC,OR] RewriteCond %{HTTP_USER_AGENT} "symbian|midp|wap|phone|pocket|mobile|pda|psp" [NC] RewriteRule ^([^.])\.php$ /mobile_$1.php [L] "
What this does:
Turns on the redirecting engine in apache
Rewrites all php ONLY pages that are requsted by a user agent that matches the defined list, and adds a “mobile_” prefix.
So a mobile phone requesting www.site.com/index.php would actually get www.site.com/mobile_index.php
Reasons for doing this:
The advantages of using the .htaccess file to redirect users, as opposted to JavaScript is that you get a much faster response time for all browsers.
When running this type of JavaScript, the client browser, full or mobile, must download the entire index.php and then start rendering it, before it realizes that the file it actually wants, is mobile_index.php.
This in itself uses less than half the bandwidth, and saves processor/system resources.
The code block above can be edited to do anything, including redirect people to a static page.
-Ben
About the Author
Ben Shambaugh is a
Systems Engineer
for Special Applied Intelligence
http://www.specialai.com-progress for hire




