Modern Mobile Redirect Using .htaccess

. Filed under HowTo.

The following set of rewrite rules will redirect all Android, Blackberry, iOS, Windows and WebOS devices to a specific mobile directory on your website. Additionally, it will redirect Google’s mobile crawler — according to Google search spam czar Matt Cutts this is perfectly acceptable and even somewhat encourage.

To implement these rules:

  1. Replace “mobiledirectoryhere” with the path to your mobile site. If your mobile site is located in a subdirectory, use the full URL (including “http://”) and you can omit the first RewriteCond.
  2. Then copy & paste the ruleset into the site’s .htaccess file or the main apache configuration.

Rationale

Since the last time I wrote about mobile browser detection and redirection in 2009 the mobile device landscape has changed once again. Smartphones dominate the mobile browsing landscape and feature phones are almost not existant in server logs.

The old redirection rules I posted attempt to redirect every mobile phone under the sun. At this point in 2011, it’s probably safe to completely ignore ancient phones and simplify your Apache rules in the process.

  • Will

    Hi Ryan,

    I’ve been having a few issues with implementing your solution. My .htaccess file is:

    ————————————-
    AddType video/ogg  .ogv

    AddType video/mp4  .mp4

    AddType video/webm .webm

    SetEnvIfNoCase Request_URI .(og[gv]|mp4|m4v|webm)$ no-gzip dont-vary

    RewriteEngine On

    RewriteCond %{REQUEST_URI} !^http://smstaging.stanford.edu/pem/mobile.html.*$
    RewriteCond %{HTTP_USER_AGENT} “android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile” [NC]

    RewriteRule ^(.*)$ http://smstaging.stanford.edu/pem/mobile.html [L,R=302]

    ————————————-

    (without the dashes in the .htaccess file). The 4 top lines are because I am using “Video or Everybody” to play my video on the website and it requires that in there. I have been using an iPhone to test and it gives me the following message:

    Safari cannot open the page because too many redirects occured”

    But it does successfully take me from the mywebsite/index.html page to the mywebsite/mobile.html page, it just doesn’t render and I get that error message above. Do you know how I can fix this?

  • Will

    Sorry for posting twice, the .htaccess file came out all in one continuous line on the last post and it wasn’t very easy to read.

  • kaboom

    Nope, can someone help us out here please?

  • Will

    I’m still having the same issue as well. If I can find a different solution I’ll let you guys know. Please post here if you find a solution also. Thanks!

  • Anonymous

    The REQUEST_URI portion of the rule is matching the request URI portion of the request (ie. everything after the host name). That first line is stopping a redirection loop when you are redirecting mobile request to a subdirector. Since you are redirecting to a subdomain, you wouldn’t need that line. Also, the preceding slash in the last line is not right. 

    Try something like this:

    RewriteEngine onRewriteCond %{HTTP_USER_AGENT} “android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile” [NC]RewriteRule ^(.*)$ http://m.mysite.com/ L,R=302

  • Anonymous

    I responded to kaboom’s question above: http://ohryan.ca/blog/2011/01/21/modern-mobile-redirect-using-htaccess/#comment-266136097

    Hope that helps.

  • http://twitter.com/notian notian

    Your file should probably look more like this

    RewriteEngine on

    RewriteCond %{HTTP_HOST} !^m.mysite.com$

    RewriteCond %{HTTP_USER_AGENT} “android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile” [NC]

    RewriteRule ^/?(.*)$ http://m.mysite.com/$1 L,R=302

  • Will

    Hi Ryan,

    Thank you very much for taking the time to help us all out. I tried your code above but it didn’t work for me, and when mobile users attempted to go to the website I would get a 505 server error. Therefore I used the following code instead:

    RewriteEngine On#redirect mobile browsersRewriteCond %{HTTP_USER_AGENT} ^.*iPhone.*$RewriteRule ^(.*)$ http://mywebsite/mobile/index.html [R=301]RewriteCond %{HTTP_USER_AGENT} ^.*iPad.*$RewriteRule ^(.*)$ http://mywebsite/mobile/index.html [R=301]RewriteCond %{HTTP_USER_AGENT} ^.*BlackBerry.*$RewriteRule ^(.*)$ http://mywebsite/mobile/index.html [R=301]RewriteCond %{HTTP_USER_AGENT} ^.*Palm.*$RewriteRule ^(.*)$ http://mywebsite/mobile/index.html [R=301]

    Inside the new mobile folder I created a new .htaccess file which has the RewriteEngine Off so that there wouldn’t be the redirect issue. Despite the fact a different solution has come up, I would much rather use your solution because it covers so many different types of mobile devices. Do you have any idea what I was doing wrong when trying to use your solution? I used your most recent post verbatim, except adding in my mobile website location for the URL:

    RewriteEngine onRewriteCond %{HTTP_USER_AGENT} “android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile” [NC]RewriteRule ^(.*)$http://m.mysite.com/ [L,R=302]

    If you have any helpful hints I am all ears!

    - Will

  • Will

    Hi Mike,

    This worked for me:

    RewriteEngine On
    #redirect mobile browsers
    RewriteCond %{HTTP_USER_AGENT} ^.*iPhone.*$
    RewriteRule ^(.*)$ http://smstaging.stanford.edu/pem/mobile/index.html [R=301]
    RewriteCond %{HTTP_USER_AGENT} ^.*iPad.*$
    RewriteRule ^(.*)$ http://smstaging.stanford.edu/pem/mobile/index.html [R=301]
    RewriteCond %{HTTP_USER_AGENT} ^.*BlackBerry.*$
    RewriteRule ^(.*)$ http://smstaging.stanford.edu/pem/mobile/index.html [R=301]
    RewriteCond %{HTTP_USER_AGENT} ^.*Palm.*$
    RewriteRule ^(.*)$ http://smstaging.stanford.edu/pem/mobile/index.html [R=301]

    Inside the new mobile folder I created a new .htaccess file which has the RewriteEngine Off so that there wouldn’t be the redirect issue. However this won’t cover all mobile devices. If you have a better solution let me know.

  • Andrew

    Script works great. But isn’t it considered best practice to allow mobile users to click a link and go to the full non-mobile version of the site? It doesn’t seem like you would be able to do this using this method. Any ideas?

  • Lrpico

    Hi Ryan,
    First, apologies for bumping this up… ;-)
    Second, a big thank you for the code, after a hundred different things, I tried this and is the one that works, or sort of…
    Third, is there a way to add detection for Nokia browsers in general?

    Thanks

  • Pingback: Mobile Redirect With htaccess

  • Brian

    Thanks you

    It works like a charm

  • Nadir Hajiyani

    Hi,
    The code was working awesome until last the 5 days , folks with firefox 5 have started complaining that they cant get to the regular site on their computer and the code is redirecting them to their mobile site on their computer

  • Lrpico

    I’ve tried the code in almost every possible browser, no a hitch so far… The ONLY “problematic” browser was the Nokia’s handheld homebrew browsers.

  • Nadir Hajiyani

    Hey,
    Ya, it was working fine until a bunch of users in firefox started complaining that the website on computer still sends them to mobile website. Here is some data from analytics which shows many firefox5 calls coming in and that increased their number since other times it would mostly be iphone. So I am including that , incase if it helps. I removed the rule for now. Let me if there is a clue.

    [Mozilla/5.0 (Windows NT
    6.1; WOW64) AppleWebKit/5
    35.1 (KHTML, like Gecko)
    Chrome/13.0.782.112 Safar
    i/535.1]

    [Mozilla/5.0 (compatible;
    MSIE 9.0; Windows NT 6.1
    ; WOW64; Trident/5.0)]

    [Mozilla/5.0 (Windows NT
    6.1; WOW64; rv:6.0) Gecko
    /20100101 Firefox/6.0]

        [Mozilla/5.0 (Windows NT
    6.1; WOW64; rv:5.0) Gecko
    /20100101 Firefox/5.0]
        [Mozilla/5.0 (Windows NT
    6.0) AppleWebKit/535.1 (K
    HTML, like Gecko) Chrome/
    13.0.782.112 Safari/535.1]

    [Mozilla/5.0 (Macintosh;
    U; Intel Mac OS X 10_6_8;
    en-us) AppleWebKit/533.2
    1.1 (KHTML, like Gecko) V
    ersion/5.0.5 Safari/533.2
    1.1]
    [Mozilla/5.0 (Macintosh;
    Intel Mac OS X 10_6_8) Ap
    pleWebKit/534.50 (KHTML,
    like Gecko) Version/5.1 S
    afari/534.50]

        [Mozilla/5.0 (Windows NT
    6.1) AppleWebKit/535.1 (K
    HTML, like Gecko) Chrome/
    13.0.782.112 Safari/535.1
    ]

        [Mozilla/5.0 (Windows NT
    6.0; rv:6.0) Gecko/201001
    01 Firefox/6.0]

    [Mozilla/5.0 (Windows NT
    5.1) AppleWebKit/535.1 (K
    HTML, like Gecko) Chrome/
    13.0.782.112 Safari/535.1]

  • Lrpico

    You sure they’re not using some sort of an User Agent Switcher? Tried my mod of the code with an XP running FF 5, and it worked flawlessly…

  • http://twitter.com/soamjena Soumendra Jena

    Does it work with Motorola Droid ?

    My client said, on Droid, they get the tablet version :(

  • Anonymous

    Yes, the “android” user agent should cover all android devices including the droid.

  • Anonymous

    It’s good to see this information in your post, i was looking the same but there was not any proper resource, thanx now i have the link which i was looking for my research.… . .

    local movers toronto
    north vancouver movers

  • http://twitter.com/mmorri Mike Morris

    I was having looping redirect issues with looping on a site built using a PHP framework that redirects all $1 page requests to /index.php/$1 (CodeIgniter, WordPress and many other content management systems and frameworks do this). The above fixes weren’t working for me (was having issues with resources not loading) and putting a separate .htaccess file in a subdirectory wasn’t really an option because of the site structure, but built this solution that seems to work well:

    #modified mobile redirect
    RewriteCond $1 !^(index.php|_assets|robots.txt|favicon.ico|apple-touch-icon|mobile)RewriteCond %{HTTP_USER_AGENT} “android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|symbian|webos” [NC]RewriteRule ^(.*)$ /mobile/ [L,R=301]

    #stock framework/CMS redirect
    RewriteCond $1 !^(index.php|_assets|robots.txt|favicon.ico|apple-touch-icon)RewriteRule ^(.*)$ /index.php/$1 [L] 

    Note that the RewriteCond from the CMS has been repurposed in the mobile detection snippet with the addition of the /mobile path to the end to prevent looping or resource request redirection. The snippet is slightly modified, I added symbian to the user-agent string to detect Nokia browsers (still quite popular outside the US) and changed the redirect to a permanent (301) redirect.

  • Stubb

    This works great except for linking back to view the full site. Obviously it just loops back to the mobile site. Is there a way to set a cookie in the htaccess file to prevent this? Or something else?

  • http://www.facebook.com/people/Ryan-M-Long/100001384671125 Ryan M Long

    I used a php redirect with a cookie that allows mobile users to access the full website. I also only wanted mobile users to go to the mobile site if they are going to the homepage. (This is because we use QR Codes in printed material and offer many more pages on our full website that are indexed in Google’s mobile SERPs but we don’t have mobile pages available.) To do this, I added this code to the index.php file:

    $mobile = ‘http://mobile.mysite.com/’;

    if ((strstr($_SERVER[’HTTP_USER_AGENT’], ‘iPhone’)) && empty($_COOKIE[“mobilesitecookie”]) && $_SERVER[’REQUEST_URI’]==”/”) {
    header(“Location: ” . $mobile);
    }

    And this is the code that I put on the mobile site to make the cookie:

    function set_cookie () {
    document.cookie = ‘mobilesitecookie=mobilesitecookie; domain=.mysite.com;’;
    window.location = ‘http://www.mysite.com/‘
    }

    I then added an HTML A tag that triggers the set_cookie function.

    Enjoy!

  • Joss Vans

    Great !!!! sample
    Thanks , very much , its work GENIAL !!!

  • Forum Cognostek

    Any1 please tell the redirect script for Blackberry storm2 9550 model using javascript.

  • Engel Ralf

    Hi,
    i use the above code to deviate a cyber attack coming from a Safari 419.3 browser on a linux system. The only thing is that i can’t visit our sites through safari myself.
    RewriteCond %{HTTP_USER_AGENT} “Safari|safari|SAFARI|linux|LINUX|Linux” [NC]RewriteRule ^(.*)$ /http://fakedomain.com/ [L,R=302]
    is the code i’m using.
    my safari is v.5.1, could i somehow refine the above code to only block safari 419.3 linux but allow visits from other safari browsers?

  • Josh

    Why did you include “googlebot-mobile”? The redirect that you are using is specifically geared towards smartphone user agents. The googlebot-mobile user agent was meant for WAP content (feature phones). The newly introduced smartphone googlebot-mobile actually masquerades as an iPhone

  • http://www.nailyener.com/ Nail

    So, how can we have a “Full Site” link on the mobile version and send the mobile visitor to the full site and keep him there? Cookies? How can we do that with .htaccess?

  • http://www.giftscoop.co.uk/ Matt

    This is just what I was looking for to “mobify” my website. Was going to go the responsive route but I feel I can deliver a better experience with a dedicated site. Thanks!

  • ohryan

    In the past, I’ve had the “full site” link go through a script that sets a cookie. Then added a rewritecond to check if the cookie is set: http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html#rewritecond

  • Idel Fuschini

    I think the best way is to use my “Apache Mobile Filter” (http://www.apachemobilefilter.org) and mod_rewrite. For example:

    #Configuration AMF Filter
    #
    PerlSetEnv AMFMobileHome /usr/local/AMF
    PerlSetEnv AMFProductionMode true
    PerlSetEnv ServerMemCached localhost:11211

    PerlTransHandler +Apache2::AMFFilter
    # or
    PerlTransHandler +Apache2::AMFFilterMemcached
    RewriteEngine on
    RewriteCond %{ENV:AMF_ISMOBILE} ^true*
    RewriteRule ^(.*)$ http://m.foo.org [R=301,L]

    Take it from: http://wiki.apachemobilefilter.org/index.php/Mod_rewrite_integration

  • ohryan

    Hey, this looks pretty snazzy!

    Good solution if you have permissions install an Apache module.

  • Pingback: Detect mobile devices using .htaccess | TechnoReaders.com

  • http://www.facebook.com/profile.php?id=100002577669657 Fedor van der Valk

    looks like this works for a lot of people :-) I’m going to try this out today.
    thank you very much. in advance :-)

  • Jesus de La Garza

    Hi, very useful topic. Thanks for sharing.
    I’ve a question, how can I prevent a couple of subdomains to get detected by this code?

    On those 2 cases (2 subdomains: some.mydomain.com & somemore.mydomain.com) I dont need to get mobile device detection.

    Thanks for your help trying to solve this case.

  • Ranjit Pradhan

    Thanks,good discussion. it is really helps a lot .

  • Ranjit Pradhan

    I have a question . if one open the mobile version in desktop, then how can it redirect to desktop version.
     

  • Justin

    How do I incorporate a visit full website link?