Redirect To A Mobile Site Using Mod_rewrite

Updated about 5 yrs, 6 mths ago (January 19, 2012). Know a better answer? Let me know!

Redirect to a Mobile Site using mod_rewrite

How to use Apache’s mod_rewrite .htaccess rules to redirect mobile devices to a different version of your site, while still allowing a “View Full Site” link.

A lot of mobile device redirects use JavaScript, which isn’t ideal as it usually means that the mobile device has to load most—if not all—of the desktop page before it is redirected. And a lot of mobile device redirects trap people with mobile devices in the mobile site. Your site’s viewers should have choice—it’s usually handy being automatically redirected to a mobile site… but if they want to use the full version of the site on their mobile device, they should be able to.

Here’s an easy way to do so, using mod_rewrite rules.

Note that this only redirects the major mobile devices in use today—it is not a comprehensive list—and does not redirect iPads (because you’d usually want the main site on them—though simply add “ipad” to the list of user agents to do redirect iPads as well).

In this specific example, the domain name is hardanswers.net—you’d replace this with your own domain—and the mobile site is hardanswers.net/mobile/—you’d modify this to suit your specific site.

# mobile site redirection
RewriteCond %{HTTP_REFERER} !^http://(.*).hardanswers.net/.*$ [NC]
RewriteCond %{REQUEST_URI} !^/mobile/.*$
RewriteCond %{HTTP_USER_AGENT} "android|blackberry|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC]
RewriteRule ^(.*)$ /mobile/ [L,R=302]

This code goes in your .htaccess file.

More Information

Information above gathered from the following sources:

 

Updated about 5 yrs, 6 mths ago (January 19, 2012). Know a better answer? Let me know!

Related categories [coloured].

User submitted comments:

Idel, about 5 yrs, 5 mths ago
Tuesday February 7, 2012 11:40 PM

Trybto use Apache Mobile Filter is a standard Apache filter for device detection and easily usable with mod_rewrite.

http://www.apachemobilefilter,org
http://wiki.apachemobilefilter.org

Comment on this article (no HTML, max 1200 characters):