Modern Mobile Redirect Using .htaccess

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..

  • Pingback: Tweets that mention Modern Mobile Redirect Using .htaccess | OhRyan.ca -- Topsy.com()

  • Richard

    Hey Ryan,

    Good call – Lean & fast. If you’re looking for something a little more targeted (eg Android Tablets) check out Handset Detection (www.handsetdetection.com). It uses explicit http header matching against a database of known devices.

    Cheers
    Richard

  • Anonymous

    You charge $13 – $547 per month?! Jeez, I should have thought of this!

  • Pingback: Redirect to a mobile site, unobtrusively | Boulder Information Services()

  • Sabrina Morgan

    Hi Ryan,

    Thanks for posting this! Unfortunately I’ve been having a beastly time setting up a mobile redirect from my main site to a subdomain on my main site (http://m.mysite.com). The kicker is I need deep links on the main site to automatically forward to the matching page on m.mysite.com for mobile viewers.

    What would be the best way to accomplish this?

  • GMG

    Thank you for the .htaccess inserts… It worked perfectly. A heck of alot better than using a bloated PHP or Javascript code that ultimately slows it down. When using mobile devices, lag time is not easily tolerated.

  • Cpaholovach

    Ryan,

    This code is a huge help for my websites. I really appreciate the simplicity and speed. I wondered if I could change out “ipad” (I would like ipad to see my desktop version) with “palmos” and add in a few more options from your 2009 post as well?

    Also, does “webos” essentially catch most of the other handheld devices?

  • Pingback: .htaccess Mobile Browser Redirect | OhRyan.ca()

  • Anonymous

    Apologies for the late response.
    Try changing the last line of the rule to: RewriteRule ^(.*)$ http://m.mysite.com/$1 [L,R=302]

    Let me know if you found different/better solution.

  • Anonymous

    If you want iPads to see the desktop version of your site, you can just removed “ipad”.

    “webos” covers most palm & HP devices running webOS, as far as I understand you’ll have to include “palmos” to catch early webOS devices like the Palm Pre and Pixi.

    Hope that helps.

  • Pingback: Revisiting Mobile Redirection Using .htaccess ReWrite Rules | OhRyan.ca()

  • George

    Thanks for posting this Ryan !

    Would the bypass-option still work ? (I have no experience with cookies yet :P)

    RewriteCond %{HTTP_COOKIE} !^.*bypass.*$ [NC]

  • Anonymous

    I don’t see why not (but have not tested it myself).

  • kaboom

    Maybe a stupid question but what am I doing wrong here? I changed ‘mobiledirectoryhere’ with my subdomain ‘http://m.mysite.com’ and added the code. Now my site doesn’t open on iPhone with an error message ‘Safari cannot open the page because too many redirects occurred’. Thanks

  • George

    I had the exact same problem. Put an empty .htaccesd file in you mobile subdirectory and try again… Let me know.

  • George

    .htaccess

  • kaboom

    Thanks George, still the same problem..

  • kaboom

    I must be doing something wrong I guess..

    These are the 4 lines that my .htaccess file contains:

    RewriteEngine on
    RewriteCond %{REQUEST_URI} !^/http://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/ [L,R=302]

  • kaboom

    I must be editing the wrong htaccess file I guess..

    I have 4 websites in the same hosting account (each of them in separate folders such as /www/mysite1, /www/mysite2, etc) and I only need to edit redirect for one of the websites. So the htaccess file I’m editing is the one in the following folder /www/mysite1 (or /public_html/mysite1).

    I noticed that there are other htaccess files, not in website folders. One is in /www (and /public_html) folder, and in other various folders such as /www/_private, /www/_vti_bin, /www/_vti_cnf, /www/_vti_pvt.

    Sorry if it looks a dumb question but could someone guide me please?

    Thanks!

  • Dan

    I’m new to htaccess. I copy and pasted this into my file, but nothing happens. Am I missing any additional code to open or end this command?

  • Anonymous

    Have you replaced “mobiledirecotyhere/” with the path of your mobile content?

  • Great script, thanks!
    Since Android tablets exclude “mobile”, but still use “Android”, how would I redirect only iPads and Android tablets to a tablet or full site?

  • BJC

    I was so excited to find this today, but unfortunately it’s not working for me even though I have done everything correctly.

  • Many thanks for this snippet. Have been trying to solve this for days and this worked!!

  • Veloval

    Hi Ryan, I don’t know what is it that i’m doing, but it’s timing out on me (too many redirects). May be because I’m forcing the index? My main site is site/EN/index.html and site/ES/index.html. I’m using a 301 redirect to force it.

  • Great post Ryan, but I have one question.  How do you make that RewriteCond negative for non mobile browsers?

    For example, this doesn’t work. I get internal server errors:
    [code]

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

    RewriteRule ^cloud /free-cloud-assessment.php [L,R=301]

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

    RewriteRule ^cloud /what-is-the-cloud.php [L,R=301]
    [/code]

    How do you take /cloud and send it to one destination for mobile and another destination for non-mobile browsers?

  • Anonymous

    Like you said on twitter, putting the non-mobile version in /cloud and redirecting mobile UAs somewhere else, works. 

    But you answer your question, I think a negative RewriteCond would look something like: 

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

  • Phil

    Thanks for the post… I’ve found that this is the easiest and most concise redirect for mobile sites, from what I’ve seen. However, how would I make it so that the file structure is preserved? Here’s my code right now:

    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]

    I’m trying to make it, so that, for example, if someone on a mobile browser types in http://www.mmisi.com/companies.php, they get redirected to http://www.mmisi.com/mobile/companies.php, instead of http://www.mmisi.com/mobile. Thanks.

  • Phil

    Also, what would you suggest as far as adding an opt-out, or “Full Version” link?

  • Don Barthel

    Just a note, I’m with the Webfaction host and for my static/PHP site I needed this extra line at the top of my .htaccess file to make your script work:

    RewriteEngine OnThanks much for your script, it works great!

  • Don Barthel

    RewriteEngine On

  • Alseaf3

    I want to redirect all non-mobile users to a message saying ‘please visit us on a mobile device’. How do i do that?

  • Anonymous

    Thanks for the post. Helped me a lot. I’m still fighting how to redirect non-mobile to the root of the site. However, I found this interesting piece of .htaccess code: http://www.gpf-comics.com/mobile_rewrite_tests.txt if it helps anyone

  • Andrew

    Much appreciated. For anyone who can’t get this working right off the bat, add:
    RewriteEngine On 

    …before the first line.

    Andrew.

  • cwhitmore

    This is the best (and lightest way) I’ve seen to do this yet.  Nice snippet!  Quick question though…

    How do you handle a person that wants to view the full or “desktop” version of the site on their mobile device?

  • Anonymous

    Thanks! 

    The easiest way to allow a person to view the desktop version would be to allow them to opt-out of the mobile redirect with a cookie. 1. Create a link that sets a cookie (server-side or onclick with javascript); 2. check for the cookie in the re-write rule (See doc).

  • mike

    Hi Ryan, Like some others in this discussion, I’m having problems with a “Too many redirects” error when trying to access my mobile subdirectory. Here is my code:

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

    Any help is appreciated.
    Thanks

  • Arky Sparky

    In regards to desktop view, there is a better way then cookie staff (what if cookies are disabled?), simply go for MVC and create 3 pages: one for desktop in root (index.php with htaccess staff for mobile), second for mobile with htaccess for desktop (/mobile/index.php – here put link with get var, holding desktop value and check its value in controller class for mobile, if it is true go to third point), third create folder FULL VIEW or whatever, and here in htaccess override rule from root htaccess (without that mobile detector) and put path to MVC classes from root: _autoload($class_name) ./class_name.php”;}. Just for those who are not familiar with MVC, we have the same index.php as in root and still using main classes, just htaccess is different! Good Luck

  • Arky Sparky

    Well well Arky, you re improving your English, should be stuff. Winnipeg? I know who Johnny Kent was! Keep going Canadians!!!!

  • Sam posted

    Hi,
    Its a very helpful script, pardon my naivety but where would one add the url for the mobile site to which we want to redirect to?
    Thanks for the example.

  • Anonymous

    Replace the “/mobiledirectoryhere/” portion of that line.

  • Ohryan,
    Ya did that and your script surely helps. My earlier question was referring to http://www.gpf-comics.com/mobile_rewrite_tests.txt script where it was not obvious where to pit the url unlike your helpful script. Though I did check out basic rewrite tutorials and those helped as well. Your script is kool.

  • Ibrazil

    Thank you for the simple implementation. However I am trying to implement the above code with a htaccess code used to eliminate the file extension from the webpage filename. see below:

    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^XXXXXX.com$ [OR]
    RewriteCond %{HTTP_HOST} ^www.XXXXXX.com$
    RewriteRule ^/?$ “http://www.XXXXXX.com” [R=301,L]
    RewriteRule (.*).htm$ $1.php [L,QSA]
    Options +FollowSymLinks
    Options -Multiviews
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^.]+)$ $1.php [NC,L]
    RewriteEngine On
    Options -MultiViews

    With the above code I am unable to visit the mobile website in a subdirectory called m.XXXXXX.com

    any suggestions

  • Anonymous

    I’m not sure I understand the question. Is the redirect not working? Or the filename rewrite not working on the redirect page?

  • Ibrazil

     Thanks for the reply. The above code works for eliminating the file extension when navigating to a webpage.

    e.g. http://www.xxxxxx.com/page instead of http://www.xxxxxx.com/page.php

    How would I integrate the mobile redirect with this code?  

  • This is the fix to stop the redirect root.

    RewriteCond %{REQUEST_URI} ^/(stats/|missing.html|failed_auth.html|error/).* [NC]
    RewriteRule .* – [L]
     
    RewriteCond %{ENV:REDIRECT_STATUS} 200
    RewriteRule .* – [L]

  • Really great post, thanks!!

    Add this code to an .htaccess file in the directory in which the redirect is pointing to and the redirect loop will stop.

    RewriteCond %{REQUEST_URI} ^/(stats/|missing.html|failed_auth.html|error/).* [NC]
    RewriteRule .* – [L]
     
    RewriteCond %{ENV:REDIRECT_STATUS} 200
    RewriteRule .* – [L]

    Not my work.
    http://www.askapache.com/htaccess/mod_rewrite-tips-and-tricks.html

  • Anthony T.

    I am sooooo a NuB to this. I need to know what line to put into .htaccess for the following.

    I have the regular site (flash).  but need any and all ios to goto /ios/index.html

    Am I totally missing something from your main post?

    Thank  you, I have been looking for assistance for a few months. (now know it is doable in .htaccess file.

    btw.  (using standard html, no php)

  • Dan

    Did you get a resolution to the “too many redirect” problem?  I’m having the same issue?

    Thanks

  • Will

    Hi Ryan,

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

    ————————————-
    AddType video/ogg  .ogvAddType video/mp4  .mp4AddType video/webm .webmSetEnvIfNoCase Request_URI .(og[gv]|mp4|m4v|webm)$ no-gzip dont-varyRewriteEngine OnRewriteCond %{REQUEST_URI} !^http://mywebsite/mobile.html.*$RewriteCond %{HTTP_USER_AGENT} “android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile” [NC]RewriteRule ^(.*)$ http://mywebsite/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

    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/ %5BL,R=302%5D

  • 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.

  • 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 %5BL,R=302%5D

  • 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…

  • 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

  • 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?

  • 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

  • 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?

  • 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()

  • 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?

  • Justin

     Has anyone figured out how to have an op-out “Full Version” link –

  • Work like a charm!

  • VicoG

    Thank you very much! This is an great tip when you have a folder mobile version. Example: http://www.domain.com/m/

  • math

    Great
    Thank you very much for share …

  • Manoj

    It is the best solution for normal redirection. thanks man.

  • joseph

    can anyone help me with this

    RewriteEngine on

    RewriteCond %{HTTP_USER_AGENT} android [NC,OR]

    RewriteCond %{HTTP_USER_AGENT} opera mini [NC,OR]

    RewriteCond %{HTTP_USER_AGENT} blackberry [NC,OR]

    RewriteCond %{HTTP_USER_AGENT} iphone [NC,OR]

    RewriteCond %{HTTP_USER_AGENT} (pre/|palm os|palm|hiptop|avantgo|plucker|xiino|blazer|elaine) [NC,OR]

    RewriteCond %{HTTP_USER_AGENT} (iris|3g_t|windows ce|opera mobi|windows ce; smartphone;|windows ce; iemobile) [NC,OR]

    RewriteCond %{HTTP_USER_AGENT} (mini 9.5|vx1000|lge |m800|e860|u940|ux840|compal|wireless| mobi|ahong|lg380|lgku|lgu900|lg210|lg47|lg920|lg840|lg370|sam-r|mg50|s55|g83|t66|vx400|mk99|d615|d763|el370|sl900|mp500|samu3|samu4|vx10|xda_|samu5|samu6|samu7|samu9|a615|b832|m881|s920|n210|s700|c-810|_h797|mob-x|sk16d|848b|mowser|s580|r800|471x|v120|rim8|c500foma:|160x|x160|480x|x640|t503|w839|i250|sprint|w398samr810|m5252|c7100|mt126|x225|s5330|s820|htil-g1|fly v71|s302|-x113|novarra|k610i|-three|8325rc|8352rc|sanyo|vx54|c888|nx250|n120|mtk |c5588|s710|t880|c5005|i;458x|p404i|s210|c5100|teleca|s940|c500|s590|foma|samsu|vx8|vx9|a1000|_mms|myx|a700|gu1100|bc831|e300|ems100|me701|me702m-three|sd588|s800|8325rc|ac831|mw200|brew |d88|htc/|htc_touch|355x|m50|km100|d736|p-9521|telco|sl74|ktouch|m4u/|me702|8325rc|kddi|phone|lg |sonyericsson|samsung|240x|x320|vx10|nokia|sony cmd|motorola|up.browser|up.link|mmp|symbian|smartphone|midp|wap|vodafone|o2|pocket|mobile|treo) [NC,OR]

    RewriteCond %{HTTP_USER_AGENT} ^(1207|3gso|4thp|501i|502i|503i|504i|505i|506i|6310|6590|770s|802s|a wa|acer|acs-|airn|alav|asus|attw|au-m|aur |aus |abac|acoo|aiko|alco|alca|amoi|anex|anny|anyw|aptu|arch|argo|bell|bird|bw-n|bw-u|beck|benq|bilb|blac|c55/|cdm-|chtm|capi|cond|craw|dall|dbte|dc-s|dica|ds-d|ds12|dait|devi|dmob|doco|dopo|el49|erk0|esl8|ez40|ez60|ez70|ezos|ezze|elai|emul|eric|ezwa|fake|fly-|fly_|g-mo|g1 u|g560|gf-5|grun|gene|go.w|good|grad|hcit|hd-m|hd-p|hd-t|hei-|hp i|hpip|hs-c|htc |htc-|htca|htcg|htcp|htcs|htct|htc_|haie|hita|huaw|hutc|i-20|i-go|i-ma|i230|iac|iac-|iac/|ig01|im1k|inno|iris|jata|java|kddi|kgt|kgt/|kpt |kwc-|klon|lexi|lg g|lg-a|lg-b|lg-c|lg-d|lg-f|lg-g|lg-k|lg-l|lg-m|lg-o|lg-p|lg-s|lg-t|lg-u|lg-w|lg/k|lg/l|lg/u|lg50|lg54|lge-|lge/|lynx|leno|m1-w|m3ga|m50/|maui|mc01|mc21|mcca|medi|meri|mio8|mioa|mo01|mo02|mode|modo|mot |mot-|mt50|mtp1|mtv |mate|maxo|merc|mits|mobi|motv|mozz|n100|n101|n102|n202|n203|n300|n302|n500|n502|n505|n700|n701|n710|nec-|nem-|newg|neon|netf|noki|nzph|o2 x|o2-x|opwv|owg1|opti|oran|p800|pand|pg-1|pg-2|pg-3|pg-6|pg-8|pg-c|pg13|phil|pn-2|pt-g|palm|pana|pire|pock|pose|psio|qa-a|qc-2|qc-3|qc-5|qc-7|qc07|qc12|qc21|qc32|qc60|qci-|qwap|qtek|r380|r600|raks|rim9|rove|s55/|sage|sams|sc01|sch-|scp-|sdk/|se47|sec-|sec0|sec1|semc|sgh-|shar|sie-|sk-0|sl45|slid|smb3|smt5|sp01|sph-|spv |spv-|sy01|samm|sany|sava|scoo|send|siem|smar|smit|soft|sony|t-mo|t218|t250|t600|t610|t618|tcl-|tdg-|telm|tim-|ts70|tsm-|tsm3|tsm5|tx-9|tagt|talk|teli|topl|hiba|up.b|upg1|utst|v400|v750|veri|vk-v|vk40|vk50|vk52|vk53|vm40|vx98|virg|vite|voda|vulc|w3c |w3c-|wapj|wapp|wapu|wapm|wig |wapi|wapr|wapv|wapy|wapa|waps|wapt|winc|winw|wonu|x700|xda2|xdag|yas-|your|zte-|zeto|acs-|alav|alca|amoi|aste|audi|avan|benq|bird|blac|blaz|brew|brvw|bumb|ccwa|cell|cldc|cmd-|dang|doco|eml2|eric|fetc|hipt|http|ibro|idea|ikom|inno|ipaq|jbro|jemu|java|jigs|kddi|keji|kyoc|kyok|leno|lg-c|lg-d|lg-g|lge-|libw|m-cr|maui|maxo|midp|mits|mmef|mobi|mot-|moto|mwbp|mywa|nec-|newt|nok6|noki|o2im|opwv|palm|pana|pant|pdxg|phil|play|pluc|port|prox|qtek|qwap|rozo|sage|sama|sams|sany|sch-|sec-|send|seri|sgh-|shar|sie-|siem|smal|smar|sony|sph-|symb|t-mo|teli|tim-|tosh|treo|tsm-|upg1|upsi|vk-v|voda|vx52|vx53|vx60|vx61|vx70|vx80|vx81|vx83|vx85|wap-|wapa|wapi|wapp|wapr|webc|whit|winw|wmlb|xda-) [NC,OR]

    RewriteCond %{HTTP:Accept} (text/vnd.wap.wml|application/vnd.wap.xhtml+xml) [NC,OR]

    RewriteCond %{HTTP:Profile} .+ [NC,OR]

    RewriteCond %{HTTP:Wap-Profile} .+ [NC,OR]

    RewriteCond %{HTTP:x-wap-profile} .+ [NC,OR]

    RewriteCond %{HTTP:x-operamini-phone-ua} .+ [NC,OR]

    RewriteCond %{HTTP:x-wap-profile-diff} .+ [NC]

    RewriteCond %{QUERY_STRING} !noredirect [NC]

    RewriteCond %{HTTP_USER_AGENT} !^(Mozilla/5.0 (Linux; U; Android 2.2; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1 offline)$ [NC]

    RewriteCond %{HTTP_USER_AGENT} !(windows.nt|bsd|x11|unix|macos|macintosh|playstation|google|yandex|bot|libwww|msn|america|avant|download|fdm|maui|webmoney|windows-media-player) [NC]

    RewriteRule ^(.*)$ http://mediarightsagenda.net/ [L,R=302]

    php_value error_reporting “E_ALL ^ E_WARNING ^ E_NOTICE”

    # BEGIN WordPress

    RewriteEngine On

    RewriteBase /

    RewriteRule ^index.php$ – [L]

    RewriteCond %{REQUEST_FILENAME} !-f

    RewriteCond %{REQUEST_FILENAME} !-d

    RewriteRule . /index.php [L]

    # END WordPress

    ———————————————————-
    am trying to stop this from redirecting on mobile browsers..thanx

  • Teresa Swett

    Thanks a lot, this really is a truly awsome article! That helped me a lot. I would like to share with you a great service to fill a form online. Try PDFfiller to fill IRS 1040 – Schedule E here http://goo.gl/pl4aKW. It allows you to to fill out PDF files.