Treehouse: Grow your CSS skills. Land your dream job.

Last updated on:

Redirect Mobile Devices

<script type="text/javascript">
if (screen.width <= 699) {
document.location = "mobile.html";

"mobile.html" would be replaced with the location of wherever your mobile version resides. This technique could be adapted to load an alternate stylesheet as well.

For iPhones/iPods Specifically

<script language=javascript>
if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {


  1. anon
    Permalink to comment#

    Nice and concise! thanks

  2. Thanks a lot @anon. I find it very useful also.

  3. Permalink to comment#

    no safari

  4. What if mobile phone can not use JavaScript?

    • Did you ever get an answer to your question? I have the same concern.


    • pcacesam

      USE PHP!!! :D

      I use this

      you’ll have to change the extension on your page from .html or .htm to .php so the server knows to process the script. Also this needs to be before the <html tag – ie the first line on the page. To add a device just add it to the if statement under the mobileDevice() function

    • pcacesam

      function mobileDevice()
      $type = $_SERVER[‘HTTP_USER_AGENT’];
      if(strpos((string)$type, “Windows Phone”) != false || strpos((string)$type, “iPhone”) != false || strpos((string)$type, “Android”) != false)
      return true;
      return false;
      if(mobileDevice() == true)

    • It should work with major smartphones (eg iPhone, Driod, Blackberry, ex.) If the phone can’t read Java, then unless your website is only text, it won’t be able to read your website anyways… But this link was tons of different methods like PHP

    • Sambhav Karnawat
      Permalink to comment#

      This code does not work on javascript-disabled phones or browsers. But most of the smartphone users these days have javascript enabled.

  5. Fernando Sanches

    But and devices that do not work with javascript?

    • Hello World
      Permalink to comment#

      Most devices now-a-days do have javascript capabilities.

  6. in the iPad/iphone version.

    Is it suppose to say…
    “navigator.userAgent.match(/iPod/i” or
    “navigator.userAgent.match(/iPad/i” ????

  7. Nate Paul
    Permalink to comment#

    This works great!

    One thing: Once a mobile user logs onto the site it takes them to the mobile site. I want to let them be able to go to the full-version site. But of course when they click on the link, it redirects them to the mobile site.

    Any help is appreciated!

    • You ever get an answer back on this? I was wondering the same thing.

    • Geoffrey Freedom
      Permalink to comment#

      Why don’t you just clone the non mobile site(w/out the javascript mobile redirect) and make it index1.html and make that the link from the mobile site?

    • I used the clone methed(by geoffrey Freedom) and it works great, I only did it for the home page so “index1.html” has no flash so the handhelds can display the images I use with jquery if they use the full site.

    • Permalink to comment#

      Google penalizes for duplicate content, so when cloning your index (or any page) may want to create a mostly new way to write the page content.

    • Gavin
      Permalink to comment#

      for the clone website you can just add the no follow meta tag on the clone. that way google won’t penalize you.

    • x
      Permalink to comment#

      Set a cookie.
      Interaction w/ the cookie can save the value of if the user wants the mobile or full site, or simply the presence of can be used to continue the function or die.

      Wrap your switcher in a if/then statement, and if the user chooses to go to the full site, it sets the cookie and reloads. The reload will run through the if/then switcher, but by adding a line to check if cookie exists, that means if it does then the user opted IN for the full site and OUT of mobile, sending to mobile sheets or mobile site stops right there, no duplication of content, saves your google ranking and to undo the no-mobile, they simply clear the cookie. No cookie? Then the user detection runs, picks mobile or full until the user decides otherwise.

      Its kind of cobbling old school to new school, but it does let you set a reference point per user without building a whole redundant site for a what if situation…

    • Permalink to comment#

      If you have not managed to get round this yet. To get round the looping caused by this problem, you need to clone the index.htm file and name the new file index1.htm. Then the latter page is the point of destination when the full web button is pressed.

    • I think cloning the index has other issues. I find the best simple solution (without messing with cookies) is to set another if statement within the script

      if &ltscreen.width &lt= 699) {
      if (document.referrer.indexOf(‘mobile.html’) == -1){
      document.location = “mobile.html”;

      In english that’s

      “if the screen width is less than 699px,
      and I am not already coming from the mobile page,
      send me to the mobile page”

    • Thanks Shawn Taylor – your solution worked perfectly!

    • josh
      Permalink to comment#

      THis is not working for me how would i put this?

      if &ltscreen.width &lt= 699) {
      if (document.referrer.indexOf(‘mobile.html’) == -1){
      document.location = “mobile.html”;

    • Sorry, I messed up the code-in-comment specifics… here you go:

      if (screen.width &lt= 699) {
      if (document.referrer.indexOf(‘mobile.html’) == -1){
      document.location = “mobile.html”;
    • Argh – still messed it up, and can’t see how to edit a comment – that &lt should be a smaller than symbol… I’ll try again:

      if (screen.width <= 699) {
      if (document.referrer.indexOf(‘mobile.html’) == -1){
      document.location = “mobile.html”;

      ps – anyone know how to edit a comment?

    • josh
      Permalink to comment#

      Here is what mine looks like, Without the going back to desktop works fine. Its when i put the “Desktop Site” link that gives me the problem. Thanks you in Advance for your attention.

      if (screen.width <= 699) {
      document.location = ";;

      if (screen.width <= 699) {
      if (document.referrer.indexOf(‘ == -1){
      document.location = “”;

    • Hey Josh,

      Looks like your running the redirect twice, and the first time is without any secondary if statement, so it will always redirect. you need to just run it once, with the “if from mobile, don’t redirect to mobile” if state, which is the if (document.referrer.indexOf(‘ == -1)… hope that helps.

    • Hey Nate, I simply put a link on the mobile site to the desktop site, so if anybody wants to visit that on their phone they can. Works well.

    • trashcode
      Permalink to comment#

      If a user klicks on a link on the mobile site und goes to the classic site you set a cookie.

      on the classic site you first read the cookie and only if its not available you’re going to redirect the mobile users


    • yem fab
      Permalink to comment#

      I’ve found this problem too! Please let me know if youve resolved this issue

  8. No more Mobify? You should do a post on mobile sites ;)

  9. sd
    Permalink to comment#

    thanks you men !!!!!

  10. Permalink to comment#

    Outstanding… a simple, elegant solution… thank you…

  11. dimsen
    Permalink to comment#

    How to include android phones?

    • Permalink to comment#

      works fine with android phones.

    • Marcus

      May have to make a small modification… what with the Galaxy Nexus as well as any forthcoming Android phones that have 720p resolution screens. The above code in the OP would wind up directing a GNex user to the desktop version of the site I reckon. As nice as 720p resolution is, the screens themselves are still far too small to make desktop site viewing a pleasant experience on a phone.

  12. Permalink to comment#

    Good article,
    also maybe try to check out my script called “redirection_mobile.js”. It detects the User Agent and redirects to a mobile version if you’re accessing a site from a mobile device.

    In some case you want to redirect from a mobile device to a desktop version (like with a link “Go to the main site”), the script will handle that and once you finish your session, you’ll access to the mobile version again.

    You can find the source code on github here and you can read more details in one of my article here:

    • Thanks for the code. I’ve already tried this with an iPhone 4 and it works great but, for some reason, it’s not working on a HTC Desire HD – it just goes straight to the full site. Is there a fix for this? Thanks!

    • Permalink to comment#

      Woo hoo!

      Thanks for posting the link. I tried the solution on css-tricks and it worked great. But your js solution gave me the greater control that I needed for linking back to the full version of the website.


    • kumar
      Permalink to comment#


      im new to coding..i tried this code

      if (screen.width
      . with this code the website goes perfectly to mobile version but by clicking the link (like with a link “Go to the main site”), but it don’t get back to full version of site. And also i tried u r suggesting from given link above in your post.. but i can’t get revert back the web site as full site from mobile version in mobile.

      plz give me the brief explanation and suggestion which is successfully execute how to switch the site from desktop to mobile and mobile to desktop version.

  13. Permalink to comment#

    hi its very cool thanks buddy

  14. Raden Mas Purwandharu
    Permalink to comment#

    how about for blackberry solution..
    thanks in advance.

  15. sebas
    Permalink to comment#

    Thank you very much!!!

    Ive been searching for this code all day!!:D

  16. Permalink to comment#

    great thanks

  17. Permalink to comment#

    Once changed to window.location it worked! Thanks!

  18. Nice. Thanks this worked on my iPod but not on the iPad.

    iPads are ok for regular sites because the screen is big enough.

    Can someone list which mobile devices this script works on?


    • It works on any device with a screen width below 699 pixels. This includes iPhone/iPod 4g with retina display. You can adjust the 699 to a higher number, but I would not because of old monitors with a 700 width.

      If you are targeting iOS devices, you can use the second one, editing

      if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {


      if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || navigator.userAgent.match(/iPad/i))) {

      By standards, it works on any device with a screen width below 699, and JavaScript enabled. But there are always exceptions. (Like CSS3 in IE6, for example).

    • steve
      Permalink to comment#

      Hey Mooseman,

      I tried swapping in your code for this to work on ipads, but when I did dreamweaver told me that there was a syntax error on the edited line. Any suggestions as to how I could fix that? Thanks so much.


  19. is this redirect seo friendly

    after implementing this for a mobile site

    my Google ranking went down and i am wondering if this affected my seo

  20. SIrish

    As I understand it, the code is on the full-screen site, it just redirects, so the phone doesn’t have to use java.

  21. Awesome trick! Thank you, i’ll use it on my tumblr blog. :)

  22. Can any one have idea to solve through .httaccess?

  23. Hi,

    How to redirect …desktop/page1.html to …mobile/page1.html, …desktop/page10.html to …mobile/page10.html…etc…for more than 300 pages.
    So not just to …mobile/index.html

    Thanks for your help

  24. If you redirect via the Location object you will lose the HTTP referrer from the original request. This means all of your mobile traffic will appear as direct traffic in your analytics.

    I think server-side detection is preferred. Some options:

  25. Thank you so much! Works perfectly and so simple!!!

  26. Jonathan
    Permalink to comment#

    Very nice work on this! Took me a lot of searching but this is what we needed.

  27. Tregenza
    Permalink to comment#

    That’s so helpful, thank you!

  28. JavaScript doesn’t work at all… so I decided to use the .htaccess file to redirect mobile devices.

    Consider, if someone doesn’t want to redirect to the mobile version of your site implement a “Regular Site” button on the mobile version.

  29. Thank you so much for this javascript code!

  30. Amit Jadhav
    Permalink to comment#

    Thank You so much for provide dis easy code :)

  31. era
    Permalink to comment#

    i would choose media querries…so i can handle it with css and i dont need a 2nd (?) website with the same structure & (maybe)content :-)

  32. Permalink to comment#

    a good server-side (php) script about this application can be found at

    • Eneko
      Permalink to comment#

      isAndroid(), isBlackberry(), isOpera(), isPalm(), isWindows(), isGeneric()…

      and the isIOS mode?

  33. Permalink to comment#

    Awesome, thanks so much for this, helped me tons !!

  34. Permalink to comment#

    Need a script like this for a client. Works perfectly. now they can have just the tools from our site in a mobile device rather than the whole site. Love it.

  35. Permalink to comment#

    Thanks for a quick, simple solution!

  36. Permalink to comment#

    Wonderful code, thanks for the tip…

  37. Andrew
    Permalink to comment#

    I pasted the code, and when I load the page on my iPod touch, i get “Page Not Found”…any suggestions?

  38. Permalink to comment#

    Great script — thanks

  39. Natalie
    Permalink to comment#

    I can’t tell you how happy I was that this actually worked the first time I tried it, thanks for making my life so much easier!!!

  40. Thanks! Great script, simple solution, love it.

  41. Cucho
    Permalink to comment#

    Another solution using php can be:

    if(strstr($_SERVER[‘HTTP_USER_AGENT’],’iPhone’) ||

    else if(strstr($_SERVER[‘HTTP_USER_AGENT’],’iPad’))




    You can add “else if” alternatives for other user agents. Of course it works in servers with php support.


  42. Great script. I’ve been using it for a couple of weeks and it works for everyone that has used it, but for one. He has an iPhone 4 and it keeps giving him the old landing page. The script isn’t redirecting him.

    I asked if his javascript was turned off and he said no. The odd thing was the link worked for him earlier. I wonder if his cache, cookies or history are screwing him up?

    Has anyone had any problems like this before?

    The site is

  43. LA
    Permalink to comment#

    If I have a home for iPhone, a home for Droids and a home for computer browsers, in order to send visitors in one of three directions, do I insert the script like this:

    <!–if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) { location.replace(“http://url-to-send-them/iphone.html”);}–>

    <!–if (screen.width


  44. fabien egot
    Permalink to comment#

    When I’m trying to add Android, my iPad is not redirected anymore.
    My code is:

    if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)))
    else if(navigator.userAgent.match(/iPad/i)) || (navigator.userAgent.match(/Android/i)))

    Any idea ?

    • thankU
      Permalink to comment#

      else if(navigator.userAgent.match(/iPad/i)) || (navigator.userAgent.match(/Android/i)))

      It’s error.

      else if((navigator.userAgent.match(/iPad/i)) || (navigator.userAgent.match(/Android/i)))

  45. César
    Permalink to comment#

    You saved my life! Thank you!!

  46. Permalink to comment#

    This technique is very intuitive, but a PHP detect/redirect is more efficient. Check out the following site for a complete detect/redirect, and option to view full site:

  47. Dave
    Permalink to comment#

    This is an odd one, but is there a way to do the reverse. I’ve built a mobile site and I want to direct people if they land on this URL to another site.

  48. Permalink to comment#


    You can redirect using .htaccess. I am kinda confused about what you are trying to do though. Are you wanting to redirect everyone that lands on your mobile page to another site??

  49. Dave
    Permalink to comment#

    I’ve built a site using WordPress that is only for mobile users. Because of the contract with the festival…I need to send desktop users to the main website and not the mobile one I created.

    I guess if I don’t advertise the URL it won’t matter anyway, and they can direct mobile users from there site to mine.

    But I guess regardless I’d like to have nobody viewing the mobile site that I created on a desktop.


  50. Permalink to comment#

    You saved me! This is just how great, for me as a “non-developer” this was awsome, when i just “launched” the mobilesite for our event! Thanks again!

  51. Jewell
    Permalink to comment#

    just what i was looking for …….

  52. Permalink to comment#

    this works great… but how can i re-direct users back to the main site from their mobile devices if they want to see the desktop web version of the website? thanks.

    • Permalink to comment#

      Set a cookie when they visit the mobile site, and check for the cookie prior to the redirect.

      A complete solution for redirect/ view full site using php can be found at the following:

    • Permalink to comment#

      Thanks Matt… this php script is very glitchy. I implemented everything properly, but sometimes it directs to the mobile site, other it just doesn’t. Also, it seems like the only way to redirect from Mobile to Full site is by making the link with with double slash at the end (weird, not sure why)…
      One question: in the link you provided, the article mentioned this line of code:

      setcookie("mobile","m", time()+3600, "/");

      Where should I put that?
      Thanks a lot.

    • Permalink to comment#

      That goes on your mobile page. It sets the cookie to bypass the mobile redirect when you want to view full site.

    • Permalink to comment#

      That goes on your mobile page. It sets the cookie to bypass the mobile redirect when you want to view full site.

    • Permalink to comment#

      I have not seen it acting glitchy. The code you are talking about should be placed on the mobile index page. That is the PHP code that will set the cookie to override the mobile redirect when you try to view your full site.

  53. Permalink to comment#

    Best way i found is;


    • Permalink to comment#


    • Vic
      Permalink to comment#

      You could actually as well check if the user’s browser accepts mime types with WML. If it does then it’s probably a mobile device. Then no need to worry about JS

  54. Permalink to comment#

    Nice little script. Where in the document do you place this js? in the head or in the body or wherever you want?

    • Permalink to comment#


    • Permalink to comment#

      I would think that this JS would go in the head, before any full-site CSS and content, therefore redirecting before loading unnecessary files. That can be slow on mobile and take up valuable KB transfer.

      I have a slightly different solution that I will post here tomorrow. It’s a different take on this awesome snippet but ads a little helper for a request that people have been asking for.

      Cool stuff CHRIS, thanks !!

  55. Permalink to comment#

    This is the best javascript mobile redirect I have found. It’s rather perfect and handles all the cookie, redirect to and fro the mobile and full site. And does it with screen width like your above script does.

  56. Permalink to comment#

    i am asking doubt about the “slide to unlock”.i want the page to redirect to another page after the unlocking
    soory for asking this the thread for unlocker was closed that’s why asked here

  57. Permalink to comment#

    i fixed it ,
    can anyone tell me how to make the slider to left side?please

  58. Ernie
    Permalink to comment#

    this seems a bad approach – you either force your mobile user to a site that is a subset of your main site, and they can’t do anything about it, or you put this snippet in every page and every new page to re-route to a mobile equivalent? Just botu workable for a small site I guess but otherwise look at something else.

  59. John
    Permalink to comment#

    Basic question: How do I manage and update a mobile subdomain so that the user can have the optionality of switching back and forth between the mobile and desktop version of the site? In other words, what is the best way to ensure that the content remains the same on both sites, and only the layouts change? Or do I have to manually update and upload the desktop site, then manually update and upload the mobile site?

  60. Brendan Mullins
    Permalink to comment#

    i like my take better :D

    function browsercheck(){
            var b=navigator.userAgent.toLowerCase();
    	for(var c=namen.length,a=0;a<c;a++)	
    	alert('not mobile')

    in the array “namen” you can add as many types as you want, as long as any of the names are somewhere in the UserAgent of the devices Browser it will return true

  61. Permalink to comment#

    Do you have to convert this to .js I get data base error.

  62. Here is more in-depth Javascript solution, provided as a library:


    Read the documentation for answers for some of the posted questions.

  63. Permalink to comment#

    Works great: I have tried it on the following page: an dit redirects perfectly but what if you want the code to activate before the page loads? For me, the page first loads and then redirects, is there anyway to get around this?

  64. Permalink to comment#

    We’re a group of volunteers and opening a new scheme in our community. Your web site offered us with valuable info to work on. You have done a formidable job and our whole community will be thankful to you.

  65. ELI
    Permalink to comment#

    Hi all i am new here and
    everyone is talking about redirect to the mobile website
    but what if i want to redirects Visitors when they try to view your WebApp or mobile site on a PC.
    i want pc users that go manualy
    can anyone do that?

  66. Keen to give this script a go.

  67. Just what I was looking for..thanks! :o)

  68. Kristi
    Permalink to comment#

    Is there a solution for Blackberry devices that can’t show flash?
    I used this code and it worked great for Iphone but not on
    older Blackberries..
    Any help would be greatly appreaciated..


  69. Damian
    Permalink to comment#

    This is a great option, but I have a question. How do you deal with users clicking a link on the mobile site to view main site? At the moment this would just end up re-directing them back to the mobile version

  70. Eli
    Permalink to comment#

    you need to duplicate the home page and remove the detection
    Script from it and have the mobile users that wants to see the full site go to it.

  71. Permalink to comment#

    This technique could be adapted to load an alternate stylesheet as well.

    Hi! no one seem taking about this option, is there an example somewhre??

    Thank you!

  72. Permalink to comment#


    I seem to have the script work on the android device, but on the iphone it goes to the same url of the android js. Has anyone else have this happen to them? It seems like the
    Android code Is being read and the

    User Agent code is not being read by iphone at all. Any ideas?


    • Permalink to comment#

      Also just noticed that when i use firefoxes User Agent switcher that the iphone 3 works..i know its a firefox addon but does that mean iphone 4 has a different user agent?

  73. Michael
    Permalink to comment#

    I’m not a coder but I pretend to be. I found the script very useful for a project I had. Now I have something similar, but instead of redirecting all mobile devices to the same mobile site I need to redirect them different sites based on the mobile device’s os. An iPhone would go to an iPhone site and an Android would go to an Android site. Any help would be greatly appreciated.

  74. Tusko
    Permalink to comment#

    thank you… great post!

  75. CR James
    Permalink to comment#

    awesome thanks! (you just ended a 5 hour headache!!) worked great!!!

  76. Joe
    Permalink to comment#

    This is a useful script. Does this work for most smart phones?

  77. This is a good script too bad you only have it available for iphone/ipod. Please expand to blackberry and android, thank you!

  78. Kim
    Permalink to comment#

    I used the script above in my header.php file for my wordpress site and it is redirecting to my mobile site perfectly.

    Now, exactly, how do I get the mobile users to go to the desktop version, if they want to, without it continuously looping back to mobile site? Alot of useful information from others is posted above, I am sure, but for someone as “green” as me, it isn;t helping because I do not know which file to change, etc.

    What I need is a way to switch mobile users ( back to desktop site (, if they choose to, without it redirecting in a loop back to mobile site all the time.

    Thank you for the help!!!

  79. Maë
    Permalink to comment#


    I plan to use the wordpress/blog url of my website to easily create a mobile version of my dreamweaver website, using a plugin). Can I then type “/wordpress ” instead of “mobile.html” to redirect mobile users to the WP mobile site, as below?

    if (screen.width

  80. Permalink to comment#

    Hey all,

    I’m utilizing the original script to run a mobile redirect and it works fabulously except I can’t figure out how to get it to redirect to a subdomain, rather than an html file in the main domain. The document location line doesn’t seem to work when the document is located in a subfolder (ie: mobile/index.html)

    Help please? I’m assuming its a simple fix.


    I’m attempting to utilize the following version of the script.

    if (screen.width

  81. Hi Mae, yes, directing it to /wordpress will work just fine.

  82. Kim
    Permalink to comment#

    Sorry to ask again, but I could really use the help…

    I used the script above in my header.php file for my wordpress site and it is redirecting to my mobile site perfectly.

    Now, exactly, how do I get the mobile users to go to the desktop version, if they want to, without it continuously looping back to mobile site? A lot of useful information from others is posted above, I am sure, but for someone as “green” as me, it isn’t helping because I do not know which file to change, etc.

    What I need is a way to switch mobile users ( back to desktop site (, if they choose to, without it redirecting in a loop back to mobile site all the time.

    Thank you for the help!!!

  83. Fabri_
    Permalink to comment#

    Hi you all.
    This code doesn not work on my web site … or with my LG Android ….
    Someone would please write some URLs where it is working properly, just to check …


  84. I think avoid Using browser javascript redirection for mobile website better to use a HTTP Server Redirection its better to avoid page loading time

  85. Permalink to comment#

    thanks everyone, I had seen the code at but wasnt sure it was good, after reading this thread I tried it and it worked! I wanted my mobile peeps to be able to break out of the mobile site and see the full site if they wanted, and all other solutions either had them stuck on the mobile or I had to make everyone land on a page to make a choice between mobile and regular, including computer people. this was a great solution! Computers go to my full site, mobile people to to the mobile site, and I have links from one too so everyone can choose to go see the other version if they want…

  86. Thanks, smart and simple!

    One mistake not to make is to put the IF statement inside an a document load. The problem this caused was that if you were to use the back button on certain phones you would end up on the main site with no document.location change so the user can’t get back to the mobile.

    Basically I added the code into the main site javascript file inside the document.load which caused this error. Then I removed the document.load wrap and everything was peachy.

    Thanks! :D

    • Hi Mark,

      You just described the problem I am trying to solve. Can you be a little more descriptive with how you solved it. I am a novice at best and am searching for an easy solution. Thanks!


    • Define easy :-D

      So when a user lands on the desktop version I would run the above resolution IF statement in-line, so there is no “$(document).ready(function(” surrounding the code. So you would place the above code simply at the top of your webpage. or in your javascript file like this

            if (screen.width <= 699) {
                   document.location = "mobile.html";

      But in my setup is is slightly different. Once the user is on the mobile sub domain I have used jquery.cookie.js to configure the rest of the process as sub domain to main domain cookie access is allowed but main domain to another main domain is not.

      If a user would actually prefer to view desktop version they would click on “view desktop version” which would create a cookie with name:mobile value:off. Then be redirected to the desktop domain. The final check done on this domain would be another IF statement run inline checking if the cookie exists and has value “off”.

      if (screen.width <= 699
         ) {
      		if( $.cookie("mobile") != null ) {
      			//alert('cookie is here'); 
      		else {
      			//alert( $.cookie("mobile") );
      			//alert('cookie is not here');
      			document.location = "";

      I have to stress that I would use responsive layouts if possible to save duplicating content/work load but this was not an option for the project I was doing.

  87. Joe


    I’m using this to test a proof of concept I have it working for iPhone, Android and Windows Mobile. Has anyone figured out a blackberry solution?


    • Hello Joe

      I was using the following script but not sure what models this works on (this was for a mobile site I built so long ago it was in tables!! :-P) so you will need to do some testing but you get the idea.

      var deviceBB = "blackberry"
      var uagent = navigator.userAgent.toLowerCase();
      var cssFile = "handheld.css";
      if ( > -1) {
      window.location = 'blackberry-home.html'; }
  88. Will this work for pages that have been “iframed” by Facebook? I ask because, at this time, Facebook tabs (pages inside a facebook page) will not resolve on mobile devices. Each Facebook tab has a unique url. But when using a mobile device, Facebook redirects those urls to the facebook log in page; after the user logs in, a facebook “page not found” error is shown. I would like instead for the mobile user to be redirected out of facebook to a clone-ish page that would display. Anyone have any experience with this?

  89. I tried this code in the head of my Genesis theme. I get “nothing found” when I Google it on my smartphone. (The mobile page worked when tested in the browser.) Any ideas?

  90. What would the screen width be for a tablet device? I would like to redirect users from the desktop version to tablet.html. Thanks!

  91. Great! Simply! Lots of thanxs

  92. Didn’t work for me…my Droid Incredible reports that screen.width = 1024.

  93. Too many geeks, no legitimate solution! Dip$3!t forum. 1-2-3- GO!

  94. hi all, i’m new here…
    please help me…

    1) i have a maindomain ( ) and a subdomain (

    2.) i’m using

    A1) @import url(“screen.css”) screen;
    A2) @import url(“mobile.css”) handheld;
    A3) @import url(“print.css”) print;
    to redirct css……

    B) only one index page called (index.php)

    3) Now i want my visitors can browse (mobile.css) via “subdomain” with desktop browser (like as on desktop)
    and visitors can browse (screen.css) via “maindomain” with mobile browser.

    sorry for bad english.

    • Mark
      Permalink to comment#

      Hi Ahmed,

      You will need to use the javascript as mentioned in the second black box here. This javascript will need to be added to the webpage:

      You will need tp create another index.php with the mobile stylesheets linked and upload this to

      For your information…..
      (You are confusing yourself here. The media resolution quiries are so that your visitors do not get re-directed to your mobile sub domain. What these do is the stylesheet is simply included for the smaller screens. This method is not needed if you are re-directing your visitors to the mobile domain where you have another index page with just your mobile css file attached)

  95. hi !Mark,
    Thanks for helpful reply,
    I’ll try that what you said…

  96. Bilal
    Permalink to comment#

    works just fine :) very easy and very useful >>> thanks
    I am using Nokia C7

  97. Elegant solution using Javascript! Here’s an article which covers mobile detection and redirection using PHP… and one that I wrote covering Perl/CGI…


  98. longo
    Permalink to comment#

    Please could you give an example for an alternate stylesheet

  99. Thanks, the javaScript it works well, interesting concept checking for screen width, just a little worried that it might have to be updated in the near future as these mobile screens get better resolutions.

    • Mark
      Permalink to comment#

      I am also a little worried about this. So far I think there is only one htc to be worried about. The way I was thinking of approaching this is if the device has a high resolution screen then treat it as such like a large screen device and show the desktop version of the site. Ideally responsive designs would take care of this issue but unfortunalty now all builds can use this.

    • Mark
      Permalink to comment#

      not all builds*

  100. Gary
    Permalink to comment#

    Has anyone tried this code on .aspx?
    I have been trying to find a script, without using .access file.
    I have tried this code on my master file however it is not working.

    Any Ideas would be much appreciated.
    Thank You

  101. Hi,

    If you want one simple code to redirect to multi devices such as feature phones, smartphones, BB, iPhone, iPad, Tab, Kindle, PSP, Nintendo wii, you should go here :

    I use it and just meet what I want. A user comes from Google to my site : example[dot]com/page_1 will be redirected right to my mobile site : m.example[dot]com/page_1 etc

  102. Gaudy
    Permalink to comment#

    How I can switch the mobile version to view full website..? But i have this code on my index page..

    if (screen.width <= 699) {
    document.location = "device.html";
    • There are a few ways, but I think a second “if” statement checking for where you’re coming from is the simplest… See my earlier comment for code (the 3rd attempt – I noobed the code-in-a-comment first 2 tries).

  103. Permalink to comment#

    You dont have to use separate user agent matches. Just separate the user agenets with a “|”…. like this…

    if ((navigator.userAgent.match(/iPhone|iPad|iPod|Windows Phone/i)))

    …then you can put as many in there as you want without the script going on too long.

  104. Permalink to comment#

    Is there any reason why this simple code wouldn’t work? I’ve got it pasted as the first JavaScript in my index.html file. But it won’t seem to work.

    Best regards,

    • Mark
      Permalink to comment#

      Hi Jeremy, have you linked to jquery file and checked validation/firebug errors?

  105. Just to let you all know I own the new Samsung Note and it works on a width of 800 so I’ve had to change my code to

    if (screen.width &lt= 801) {
    		document.location = "mobile.html";
  106. CodeMonkey
    Permalink to comment#

    Not sure that testing for resolution is accurate enough…
    I found this native JS (not reliant on jQuery) code to be pretty bullet-proof :

    var mobile = (/iphone|ipad|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));
    if (mobile) { window.location = "" }
    • Permalink to comment#

      Thank you! Thank you! Thank you!
      As far as Ive tested this it work marvelously on android and apple devices.

      In my opinion a better solution than the px width ones.

      Can other mobile devices owners please test this code:

      windows mobile

      A question for you codemonkey, what do the tags “mini” and “\sce” mean?
      Which devices do they target?

    • This code worked great for me, but is there a way to adapt it to allow for redirect back to full site from mobile site?

  107. Seaduner
    Permalink to comment#

    Can someone point me to an actual homepage that includes this code working so I can see the source in action and how it’s inserted? I can’t seem to get this working right. Thanks in advance.

  108. eric
    Permalink to comment#

    thanks!!!! working perfect

  109. Tyrone
    Permalink to comment#

    If it only worked – but it doesn’t. You can set Safari Browser to view mobile sites and this redirect just does not work. The URL of PC sites with correct redirects give mobile page views correctly in Safari. It does not work!

  110. Permalink to comment#

    This library is very good, for Mobile Detection and so simple to use..

  111. Permalink to comment#

    This works like a charm. Thank you so much. :)

  112. Gee Deezy
    Permalink to comment#

    “&ltscreen.width &lt= 699″

    Wrong! You can no longer count on pixels <699 to tell you if a device is mobile, as 2012 phones have much higher resolution, yet the screens are still relatively small.

    Even the iPad mini has 1024 pixels, so under this logic, it would not present the mobile site.

    You have to test more than just number of pixels, folks!

  113. Taylor
    Permalink to comment#

    Very useful and still very relevant. No device limitations and most should be able to handle the JS requirement just fine — thank you.

  114. MD. Saffan Alvy
    Permalink to comment#


    The javascript code in this post by the author is fine except it didn’t work for me in the android phone. Then I yield a solution. Just replace “document.location” with “window.location” and your problem is solved. For your convenience, I’m adding the full script.

    if (screen.width LESS OR EQUAL TO 700) {
    window.location = "";

    If you find it still not working, then please make sure your javascript syntax.

    • Gus
      Permalink to comment#

      Ahhhh perfect, Thank you very much!!!! Was wondering why in the world wasn’t it working on the S3 !

  115. Permalink to comment#

    This just flat out does not work! I’ve tried dozens of variations as of some of the comments here. Put the script in the header, after the title & before my css. I put the mobile.htm file in the same folder as my index.htm with the javascript, I resize the browser window and no redirect! Tried a couple of mobile emulators and still no redirect! Do you have to have some kind of .js file in your root directory too?

  116. javier
    Permalink to comment#

    Nice code

    It works
    thanks a lot

  117. Permalink to comment#

    Could someone tell me why this is not working 4 me? My index file ( has the following code, just after the head tag:


    script type=”text/javascript”>
    if (screen.width <481) {
    window.location = “”

    I reduce my screen in Firefox (also tried Explorer & Chrome) to less than 480 & it’s still the same page – no redirect. I have javascript enabled in all browsers. Why is this working 4 others & not 4 me? Am I doing something wrong? Help please.

  118. Permalink to comment#

    That’s why it’s not working? How to set a cookie then? I’m more of a designer, not a developer. Not well versed in code. thanks.

  119. Gus
    Permalink to comment#

    Hello there, I try this with my Galaxy S3 and it does not work? Any solutions?

  120. Bill
    Permalink to comment#

    No one commented on how to adapt the code to redirect to an alternate CSS page. I really don’t want to construct a new site if one page will do.

    • Anonymous
      Permalink to comment#

      @Bill you can use responsive CSS.

      nav li {
          display: inline-block;
      @media (max-width: 699px) {
          nav li {
              display: block;
  121. Permalink to comment#

    and how to make menu “Full Site”?

  122. Essam
    Permalink to comment#

    if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
    // some code..

  123. kevvvbot
    Permalink to comment#

    This IF seems to work great for me:

    if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {

    Tested on Apple iPhone 4S, Samsung Galaxy S3, Google Nexus 7

    • Permalink to comment#

      Excellent. This is one of the best mobile redirect scripts I found that works well. My old script stopped working rescently for some reason. Thanks for sharing!

  124. James R
    Permalink to comment#

    Not all wordpress sites look good on a mobile phone. What if I didn’t want to get a mobile ready theme but I wanted to do this for my wordpress site. Where would I put the suggested code. What file?

    if (screen.width

  125. Zeeshan
    Permalink to comment#

    Here’s script.

    location.href = “#”;
    else if(navigator.appVersion.indexOf(“Mac”)!=-1)
    location.href = “”;
    else if(navigator.appVersion.indexOf(“Linux”)!=-1)
    location.href = “”;;

    i want to use it as onclick function. Actually i have software site. when user click on download and then page auto redirect according to user operating system. If user OS is MAC and then redirect MAC page, if Windows and then redirect to Windows. Thanks

  126. Sarah
    Permalink to comment#

    Works like a little charm :)

  127. 112PC
    Permalink to comment#

    $iphone = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
    $android = strpos($_SERVER['HTTP_USER_AGENT'],"Android");
    $palmpre = strpos($_SERVER['HTTP_USER_AGENT'],"webOS");
    $berry = strpos($_SERVER['HTTP_USER_AGENT'],"BlackBerry");
    $ipod = strpos($_SERVER['HTTP_USER_AGENT'],"iPod");
    $wmobile = strpos($_SERVER['HTTP_USER_AGENT'],"Mobile");
    $opera = strpos($_SERVER['HTTP_USER_AGENT'],"Opera Mini");
    if ($iphone || $android || $palmpre || $ipod || $berry || $wmobile || $opera == true)
    header('Location: http://www.xxxxxx.xx/indexmobile.html&#039;);
    echo "window.location=’http://www.xxxx.xx/indexmobile.html'”;


    put it before in .php file. see it working : . Try it on a very old phone :) .Still works.

  128. saikat bepari
    Permalink to comment#

    $iphone = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
    $android = strpos($_SERVER['HTTP_USER_AGENT'],"Android");
    $palmpre = strpos($_SERVER['HTTP_USER_AGENT'],"webOS");
    $berry = strpos($_SERVER['HTTP_USER_AGENT'],"BlackBerry");
    $ipod = strpos($_SERVER['HTTP_USER_AGENT'],"iPod");

    if ($iphone || $android || $palmpre || $ipod || $berry == true)
    echo "window.location=’'”;

    and in ur index.php or home.php

    • Paul

      Just the code I was looking for. Straight forward and simple. Thanks a bunch!

  129. Barn0wl
    Permalink to comment#

    What if I want to restrict people from being able to visit the mobile site from a desktop browser? Is there an ‘statement’ that can be tacked on that would take care of that?

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

  function example() {
    element.innerHTML = "<div>code</div>";