Handling mobile redirects in .htaccess for iPhones/Androids and tablets

Below is code I put into my .htaccess to set an environment variable to change the content/theme for mobile users.


# Mobile
SetEnvIf User-Agent "Mobile" IS_MOBILE
SetEnvIf User-Agent "Googlebot-Mobile" IS_MOBILE
SetEnvIf User-Agent "BlackBerry" IS_MOBILE
SetEnvIf User-Agent "iPod" IS_MOBILE
SetEnvIf User-Agent "iPhone" IS_MOBILE
SetEnvIf User-Agent "NetFront" IS_MOBILE
SetEnvIf User-Agent "Symbian OS" IS_MOBILE
SetEnvIf User-Agent "Windows Phone" IS_MOBILE

Notice that ‘Android’ is not present in the User-Agent check. While testing with a Galaxy Nexus and Nexus 7, I noticed that the easiest way to tell the difference between Android on phones vs. Android on tablets was to check for ‘Mobile’.

From here I can access IS_MOBILE via PHP like so:


if (isset($_SERVER['IS_MOBILE'])) {
include('index-mobile.php');exit;
}

 

One thought on “Handling mobile redirects in .htaccess for iPhones/Androids and tablets”

  1. Hi, PJ —

    A web publisher should think about what kinds of features and functionality are in a mobile-optimized web page and try to ensure that only appropriate devices are redirected to that page.

    For a fancier mobile page with CSS and JavaScript and optimized for touchscreens, such as one might see on many iPhone optimized web pages, you wouldn’t want to indiscriminately redirect Symbian or BlackBerry devices as their browsers just aren’t up to snuff with modern touchscreen devices and these devices may not have touchscreens.

    I started an open source project called MobileESP in 2008 to help detect platforms and device tiers to solve this little problem. MobileESP is available in PHP, Java, ASP.NET, Python, Ruby, etc. It’s also available on the client side as a JavaScript file, though server-side detection is more effective overall. MobileESP is very easy to integrate into one’s site and very easy to customize.

    In MobileESP, there’s a concept called “tiers” to group devices with like capability together. There’s a highly capable touchscreen phone tier called, appropriately enough, the iPhone Tier, but which includes other platforms. To detect if the current device is in this tier, the web publisher simply calls this function: “DetectTierIphone()”. The function returns simple Booleans: True or False.

    For more information, including a list of all the API calls and more, please visit the web site:

    http://www.mobileesp.org

    And please feel free to contact me any time with questions or comments!

    Cheers,
    Anthony

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.