Redirect Mobile Devices Using Htaccess

Skill

Redirect Mobile Devices Using Htaccess

Posted in:

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.

Mark Tetrode
08/10/2011 - 07:57

Your article is doing a nice job, however not all mobile devices are detected.

A fairly good implementation in different languages, including apache rewrite can be found here: http://detectmobilebrowser.com/

Mark

reply

Add Comment

Put code snippets inside language tags:
[language] [/language]

Examples:
[javascript] [/javascript]
[actionscript] [/actionscript]
[csharp] [/csharp]

See here for supported languages.

Javascript must be enabled to submit anonymous comments - or you can login.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.