Redirect Mobile Devices Using Htaccess

When working with clients you always get some odd requests, well I recently was requested to redirect a particular url on a site to a third party url when someone visits from a mobile device. Now, in theory this doesn’t sound all that difficult and really there isn’t much code either. The problem is getting the exact htaccess code you need, which can be a pain especially with trying to debug mod_rewrite and Apache.

I figured I would help everyone out and plop down some code here for everyone. So, in all it’s glory I give you some rules for mod_rewrite to redirect a url on a mobile device to another url.

########## Begin – Redirect Mobile Browser Accessing /siteurltoredirect
RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC]
RewriteRule ^siteurltoredirect$ http://theendpointurl.com [R,L]
########## End – Redirect Mobile Browser Accessing /siteurltoredirect

The above code should cover all modern mobile browsers. Basically, it checks the user agent to see if the incoming is a mobile browser and then if the url requested is /siteurltoredirect it redirects it to http://theendpointurl.com. It’s as simple as that, now I hope this helps you from wasting an hour tracking down the exact syntax like I did.

Leave a Reply

Your email address will not be published. Required fields are marked *