- Как сделать редирект на мобильную версию сайта — PHP, .htaccess и HTML
- Делаем мобильный редирект на PHP
- Передача меток и субаккаунтов на мобильный лендинг с помощью PHP
- Передача UTM-меток
- Передача субаккаунтов
- Мобильный редирект в .htaccess
- Перенаправление на мобильную версию сайта в HTML (JavaScript)
- Передача меток и субаккаунтов на мобильный лендинг с помощью JavaScript
- Передача UTM-меток
- Передача субаккаунтов
- Какой способ мобильного редиректа лучше?
- Redirect Javascript: перенаправление страницы на стороне клиента
- Создание редиректа в Javascript
- Редирект при загрузке страницы
- Переадресация с таймером в Javascript
- Переадресация только для мобильных устройств
- Редирект с помощью jQuery
- Серверный редирект на мобильную версию сайта
- Redirect Mobile Devices
- Need front-end development training?
- Need front-end development training?
- Comments
Как сделать редирект на мобильную версию сайта — PHP, .htaccess и HTML
Делаем мобильный редирект 3-мя способами
Недавно один человек написал мне с просьбой подсказать, как перенаправить пользователей мобильных устройств на другую страницу. Он занимается арбитражом трафика и нужно отделить «мобильных» посетителей от «немобильных» и автоматически отправить первых на адаптированный лендинг, причём сделать это с помощью JavaScript.
Меня эта тема заинтересовала, т.к. сам я, временами занимаясь арбитражом, не догадывался автоматически разделить поток трафика исходя из устройства. Так что сейчас расскажу о 3-х способах сделать редирект на мобильную версию сайта — с помощью php, .htaccess и html (точнее — JavaScript).
Делаем мобильный редирект на PHP
Суть здесь в том, что каждое устройство сообщает серверу свой т.н. User Agent («юзер-агент»). В этом юзер-агенте находится информация о данном устройстве. Соответственно, с помощью PHP мы эту информацию извлекаем и, если по ней ясно, что устройство — мобильное, делаем редирект.
У мобильных устройств существует просто куча разных юзер-агентов. Я нашёл код, где учтены, наверное, почти все эти агенты:
Вставьте код в самое начало документа, а вместо http://site.ru/mobile/ подставьте URL, на который должны улетать мобильные пользователи. Обратите внимание, что перед этим кодом не должно быть даже пробельных символов и переводов строк — таковы уж особенности редиректов на PHP.
Передача меток и субаккаунтов на мобильный лендинг с помощью PHP
Обычно при ведении рекламных кампаний нужно получить как можно больше информации о трафике. Для этого используются, в основном, UTM-метки и субаккаунты для CPA-сетей. Хорошо бы при перенаправлении посетителя на мобильный лендинг передать и все эти данные.
Передача UTM-меток
Например, люди попадают на страницу http://site.ru/page/?utm_source=xxx&utm_medium=yyy&utm_content=zzz . Нужно, чтобы все мобильные юзеры ушли на http://site.ru/mobile/?utm_source=xxx&utm_medium=yyy&utm_content=zzz .
Для этого можно просто отрезать всё, что после ? и приклеить к мобильному URL. Однако, если исходная страница уже содержит GET-параметры, то лучше по отдельности «выцепить» все UTM-метки — это более универсальный вариант. Итоговый код получается такой:
Передача субаккаунтов
Чтобы понять принцип действия, почитайте статью про UTM-метки и субаккаунты в CPA.
Если партнёрская ссылка, по которой мобильный посетитель должен уйти, такая http://advjump.com/go/0f3c13f70409426ba0eee42428aa9b3e365b64d1eb0a0b0b/?subid=mobile-xxx&subid1=yyy&subid2=zzz , то последняя строчка в коде выше становится такой:
Т.е. здесь мы из UTM-меток получили данные для субаккаунтов.
Мобильный редирект в .htaccess
Смысл тот же — исследуем юзер-агент. Если нужно сделать перенаправление с http://site.ru/page/ на http://site.ru/mobile-page/ , то добавьте в .htaccess такой код:
Эта конструкция должна идти после строки RewriteEngine On (если её нет — добавьте).
Если же нужно отправить всех мобильных посетителей на mobile-версию сайта (с любой страницы на http://m.site.ru/ ), то последняя строчка из кода выше может иметь такой вид:
Как передать UTM-метки и субаккаунты посредством .htaccess я рассматривать не буду, т.к. много там заморочек. Да и вообще, если вы не очень понимаете представленные здесь коды, то лучше используйте вариант с PHP или JavaScript, речь о котором дальше.
Перенаправление на мобильную версию сайта в HTML (JavaScript)
Иногда нет возможности что-то редактировать на сайте на стороне сервера — например, вы используете конструктор сайтов. Тут-то и пригодится редирект на HTML, а точнее — на JavaScript, т.к. на простом HTML нужные условия не прописать.
Если нужно перекинуть мобильных юзеров на страницу http://site.ru/mobile/ , то можно использовать такой код:
В этом случае все посетители, у которых ширина экрана меньше 600 px улетят на http://site.ru/mobile/. Если нужна меньшая ширина — меняйте 600 на меньшее значение.
Передача меток и субаккаунтов на мобильный лендинг с помощью JavaScript
При перенаправлении этим способом также можно сохранить данные о трафике.
Передача UTM-меток
Если нужно, чтобы все мобильные посетители, зашедшие на http://site.ru/page/?utm_source=xxx&utm_medium=yyy&utm_content=zzz перекинулись бы на http://site.ru/mobile/?utm_source=xxx&utm_medium=yyy&utm_content=zzz , то можно использовать следующий код:
Передача субаккаунтов
Т.е. из UTM-меток получили субаккаунты.
Какой способ мобильного редиректа лучше?
По скорости перенаправления лучше PHP и .htaccess, т.к. здесь посетитель даже не видит, что его перекидывает. Однако тут всё привязано к юзер-агенту. Если у посетителя будет неизвестный юзер-агент, то редиректа не произойдёт.
С JavaScript-редиректом юзер-агент не важен, т.к. проверяется только ширина экрана. Но здесь посетитель может заметить, как сначала попадает на одну страницу, а потом его перекидывает на другую.
Так что решайте сами, какой вид мобильного редиректа вам больше по душе
Обзор партнёрской программы Studybay.com Studybay.com, это во многом уникальный международный интернет-сервис.
Как узнать посещаемость сайта? Плагин Liveinternet для Chrome. Видеоурок Итогом каких-либо действий или их отсутствия всегда является.
Как сделать динамический сайдбар в WordPress и включить виджеты? Думал просто написать о том, как можно оформить страницу 404 (Not Found).
Megapu.sh — сервис пуш уведомлений Сегодня хочу познакомить читателей моего блога с новым сервисом Push.
Как изменить заголовок статьи WordPress на H1 и зачем? Видеоурок . м (соответствующим) Title. К счастью, для того, чтобы всё это сделать, не нужно
Способ на ява скрипт наиболее оптимальный, но само перенаправление происходит медленнее.
Очень хорошая статья, но почему то у меня не работает способ Передача меток на мобильный лендинг с помощью PHP.
Может есть какая то хитрость?
А способ со скриптом не работает в некоторых телефонах, хотя разрешение у них явно меньше 800 px.
Хитростей нет, возможно, что-то упустили — не поставили кавычки где-нибудь и т.п.
Ошибка может быть либо при передаче меток на лендинг, либо при приёме их на лендинге.
Огромнейшее СПАСИБО. я все голову ломала, как перекинуть пользователей на мобильную версию, все сработало ОТЛИЧНО. Подробно и ясно, особенно для меня, чайника просто все разжевано. Еще раз вам ОГРОМНОЕ спасибо! =) =) =)
Не за что
Пиз*дец как у меня пригорело, когда не мог допереть почему у меня телефон не редиректит на мобильную версию. Это статья баян. И телефоны уже с расширениеМ экрана получше. ВЫСТАВЛЯЙТЕ СМЕЛО 1200 ЗА МЕСТО 600. *HELP* *MACHO*
Спасибо большое! Пробовал много вариантов, но именно ваш скрипт помог =)
статья очень полезная — спасибо! но в жизни вопрос гораздо сложнее))) владельцы сайтов хотят чтоб смартфоны/телефоны получали мобильную версию, но при этом видели бы кнопку или ссылку на полную версию сайта, и могли бы ее тоже открыть. а этож надо еще что-то придумывать — куки или может еще что-то
Ну да, тут попридумывать ещё надо.
Спасибо за информацию неделю маялся как с не адаптивного битрикса перекидывать на мобильную версию сайта, попробую сделать по вашей рекомендации — если получится отпишусь с рекомендацией
Петр, спасибо огромное! Статья крайне полезная и четкая.
Отдельное спасибо за информацию по передаче UTM!
Правда, лично мне, был бы крайне полезен код для переадресации с utm-метками через .htaccess. Ибо сайт сделан на Adobe Muse и со скриптом .php почему-то не получается.
Буду Вам очень признателен, если поделитесь готовым решением и для .htaccess с UTM!
Я, наверное, перерыл всю информацию о мобильных версиях в сети. Изначально хотел сделать самостоятельно отдельную мобильную версию сайта на поддомене. Но узнал, что поисковые системы гораздо лучше относятся именно к адаптации сайта под рвзные устройства. Потому что используется один контент и одна ссылка. Начал пробовать сделать адаптацию своими руками, но там очень много подводных камней. Стили нужно прописывать чуть ли не под каждый гаджет. Т.е. под каждую ширину экрана нужно создавать новые параметры отображения всех блоков. Решил найти специалиста, который разбирается в этом. Это тоже оказалось не так просто. Разброс цен аховый. От 500 руб до 100 000 руб. Понятное дело — решил начать с 500))
После общения, конечно же, оказалось что адаптация моего сайта стоит не 500 руб, а 17 000 руб)))
Но после долгих поисков нашел оптимальный вариант по всем параметрам. Адаптацию сайта поручил им mobile-version.ru и не пожалел. Сразу сказали адекватную стоимость уже на своем сайте и потом она не изменилась. Все мои пожелания выполнени и даже внесли свои предложения бесплатно! Теперь мой сайт проходит тесты от гугла, и яндекс вебмастер тоже счастлив, наблюдая за моим сайтом.
Для тех, кто еще сомневается — делать или не делать адаптацию — ДЕЛАЙТЕ. 8)
Поисковики заставят сделать мобильные версии всем сайтам. Вопрос времени.
Подскажите пожалуйста, у меня на хостинге нет поддержки php, сайт prestigechat.ru. В страницу HTML вписываю код:
Возможно, в других скриптах в коде этой страницы есть ошибки.
Источник
Redirect Javascript: перенаправление страницы на стороне клиента
Благодаря Javascript можно манипулировать передвижением пользователя с помощью перенаправлений или обновления страницы.
Для осуществления редиректа на самом деле существуют более совершенные системы, основанные на серверных языках, таких как PHP или ASP, благодаря которым можно установить, помимо его, такой статус, как, например, 301 Moved Permanently, что невозможно при использовании Javascript .
Однако, когда нет возможности работать на стороне сервера, использование Javascript является лучшим решением.
Стоит понимать, что переадресация в javascript не произойдет если клиент деактивировал такую технологию в настройках только браузера.
Создание редиректа в Javascript
Для создания редиректа с помощью Javascript нам нужно обратиться к объекту location (который является частью объекта window) и свойству href, которое произвольно устанавливается на новый URL, на который должен быть перенаправлен пользователь:
Как видите, явный вызов объекта window в данном случае необязателен, поскольку два приведенных выше кода дают одинаковый результат и оба поддерживаются разными браузерами.
В качестве альтернативы свойству href можно использовать метод replace():
Это решение, как и предыдущие, также можно считать кроссбраузерным, поэтому с практической точки зрения различные решения абсолютно идентичны с точки зрения желаемого результата.
Редирект при загрузке страницы
Иногда перенаправление запускается при загрузке веб-страницы.
Для этого наиболее часто используемая техника заключается в запуске редиректе в событии загрузки, связанном с тегом :
Переадресация с таймером в Javascript
Очень часто перенаправление с помощью javascript выполняется по таймеру, то есть по истечении всего нескольких секунд после загрузки страницы. Для получения такого же результата придется написать еще несколько строк кода, обратившись к методу setTimeout():
Переадресация только для мобильных устройств
Используя javascript, можно написать инструкции для выполнения условных перенаправлений в зависимости, например, от операционной системы или браузера, используемого пользователем.
Довольно распространенным случаем является перехват мобильных устройств с целью переадресации пользователя на оптимизированную страницу.
Для этого существует два различных метода: первый (более эмпирический) предполагает выполнение перенаправления, когда ширина экрана меньше X, а второй основан на оценке агента пользователя. Давайте посмотрим и то, и другое:
Редирект с помощью jQuery
В заключение я хотел бы отметить, что редирект также можно запустить с помощью jQuery, например, так:
Источник
Серверный редирект на мобильную версию сайта
Предлагаю вашему вниманию простое и дешевое (по ресурсам) решение для перенаправления пользователей мобильных устройств на легкую версию сайта. Решение ориентировано на highload сайты, оптимизация которых основана на кешировании гостевых запросов.
Проверка, является ли клиент мобильным устройством, производится веб-сервером nginx и в случае успеха клиент перенаправляется на поддомен или локейшн. Это существенно экономит ресурсы и позволяет добиться большей масштабируемости по сравнение с PHP методами.
Конфигурация для NGINX
Вариант №1. Мобильная версия расположена на поддомене
server < if ( $http_user_agent
* (windows\smobile|windows\sce|iphone|ipod|midp|symbian|series\s60|s60|nokia|аndroid| blackberry) ) <
rewrite ^/(.*) m.site.ru$1 permanent;
>
Вариант №2. Мобильная версия открывалась на том же домене
if ( $http_user_agent
* (windows\smobile|windows\sce|iphone|ipod|midp|symbian|series\s60|s60|nokia|аndroid| blackberry) ) <
rewrite ^/(.*)$ /liteversion/$1 last;
>
Определение мобильного устройства по $http_user_agent позволяет с высокой точностью и с минимальными затратами ресурсов отличать мобильных клиентов от обычных ПК.
Так работают Google и Yandex. Вы можете поменять user_agent своего браузера и убедится в этом.
Конечно, я не знаю, как в точности работает алгоритм определения «мобильника» в G и Y. Но я считаю, что он очень похож на элементарное регулярное выражение написанное выше.
Регулярное выражение содержит список вариаций ключевых слов в строке http_user_agent составленный на основе анализа логов нескольких сайтов. Всего проанализировано около 200 000 запросов за сутки, 5% из которых отправлено с мобильных устройств. Это гарантирует высокую вероятность выхождения в списков всех возможных вариантов user_agent мобильных устройств. Ipad я исключил из-за разрешения экрана в 1024х768px.
Надеюсь, моя заметка будет для вас полезной.
Источник
Redirect Mobile Devices
“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
Need front-end development training?
Frontend Masters is the best place to get it. They have courses on all the most important front-end technologies, from React to CSS, from Vue to D3, and beyond with Node.js and Full Stack.
Need front-end development training?
Frontend Masters is the best place to get it. They have courses on all the most important front-end technologies, from React to CSS, from Vue to D3, and beyond with Node.js and Full Stack.
Comments
Nice and concise! thanks
Thanks a lot @anon. I find it very useful also.
Works just fine with Safari on iphone for me, if you are using safari on a desktop you’ve got bigger problems.
What if mobile phone can not use JavaScript?
Did you ever get an answer to your question? I have the same concern.
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;
else
return false;
>
if(mobileDevice() == true)
header(‘Location: http://www.m-tek.biz/mobile.html‘);
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
http://www.stepforth.com/resources/web-marketing-knowledgebase/redirect-mobile-iphone-visitors-mobile-content/#.T75jTLd5mc0
This code does not work on javascript-disabled phones or browsers. But most of the smartphone users these days have javascript enabled.
But and devices that do not work with javascript?
Most devices now-a-days do have javascript capabilities.
in the iPad/iphone version.
Is it suppose to say…
“navigator.userAgent.match(/iPod/i” or
“navigator.userAgent.match(/iPad/i” .
It says iPod/iPhone version, no iPad at all
What about javascript for rails application as it is not working for mobile application?
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.
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.
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.
for the clone website you can just add the no follow meta tag on the clone. that way google won’t penalize you.
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…
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.
SIMPLES!!
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
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!
THis is not working for me how would i put this?
Sorry, I messed up the code-in-comment specifics… here you go:
Argh – still messed it up, and can’t see how to edit a comment – that < should be a smaller than symbol… I’ll try again:
ps – anyone know how to edit a 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.
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(‘http://site.com/mobile/) == -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.
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
I’ve found this problem too! Please let me know if youve resolved this issue
No more Mobify? You should do a post on mobile sites 😉
Outstanding… a simple, elegant solution… thank you…
How to include android phones?
works fine with android phones.
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.
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 https://github.com/sebarmeli/JS-Redirection-Mobile-Site 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!
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.
im new to coding..i tried this code
hi its very cool thanks buddy
how about for blackberry solution..
thanks in advance.
Did you ever find a blackberry solution? Anyone, any help is appreciated.
My blackberry curve works just great with the simple code above.
Thank you very much.
Ive been searching for this code all day. D
Once changed to window.location it worked! Thanks!
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))) <
—
to
—
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).
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.
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
As I understand it, the code is on the full-screen site, it just redirects, so the phone doesn’t have to use java.
Awesome trick! Thank you, i’ll use it on my tumblr blog. 🙂
Can any one have idea to solve through .httaccess?
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
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.
Thank you so much! Works perfectly and so simple.
Very nice work on this! Took me a lot of searching but this is what we needed.
That’s so helpful, thank you!
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.
Thank you so much for this javascript code!
Thank You so much for provide dis easy code 🙂
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 🙂
a good server-side (php) script about this application can be found at
isAndroid(), isBlackberry(), isOpera(), isPalm(), isWindows(), isGeneric()…
and the isIOS mode?
Awesome, thanks so much for this, helped me tons !!
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.
Thanks for a quick, simple solution!
Wonderful code, thanks for the tip…
I pasted the code, and when I load the page on my iPod touch, i get “Page Not Found”…any suggestions?
Great script — thanks
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.
Thanks! Great script, simple solution, love it.
Another solution using php can be:
You can add “else if” alternatives for other user agents. Of course it works in servers with php support.
Thank you for the php version.
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?
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:
When I’m trying to add Android, my iPad is not redirected anymore.
You saved my life! Thank you!!
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:
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.
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??
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.
Dave, here is a simple solution using PHP:
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!
just what i was looking for …….
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.
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:
http://www.squidoo.com/php-mobile-redirect
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 http://www.yoursite.com// with double slash at the end (weird, not sure why)…
One question: in the link you provided, the article mentioned this line of code:
Where should I put that?
Thanks a lot.
That goes on your mobile page. It sets the cookie to bypass the mobile redirect when you want to view full site.
That goes on your mobile page. It sets the cookie to bypass the mobile redirect when you want to view full site.
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.
Best way i found is;
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
Nice little script. Where in the document do you place this js? in the head or in the body or wherever you want?
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 !!
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.
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
i fixed it ,
can anyone tell me how to make the slider to left side?please
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.
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?
i like my take better 😀
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
Do you have to convert this to .js I get data base error.
Here is more in-depth Javascript solution, provided as a library:
Read the documentation for answers for some of the posted questions.
Works great: I have tried it on the following page: http://www.muqstuff.weebly.com 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?
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.
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
from http://www.mobile.domainname.com
to http://www.domainname.com
can anyone do that?
thanks
Keen to give this script a go.
Just what I was looking for..thanks! :o)
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..
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
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.
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??
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?
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?
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.
thank you… great post!
awesome thanks! (you just ended a 5 hour headache!!) worked great.
This is a useful script. Does this work for most smart phones?
This is a good script too bad you only have it available for iphone/ipod. Please expand to blackberry and android, thank you!
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 (m.mydomain.com) back to desktop site (mydomain.com), if they choose to, without it redirecting in a loop back to mobile site all the time.
Thank you for the help.
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?
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.
Hi Mae, yes, directing it to /wordpress will work just fine.
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 (m.mydomain.com) back to desktop site (mydomain.com), if they choose to, without it redirecting in a loop back to mobile site all the time.
Thank you for the help.
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 …
I think avoid Using browser javascript redirection for mobile website better to use a HTTP Server Redirection its better to avoid page loading time
thanks everyone, I had seen the code at http://detectmobilebrowsers.com/ 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…
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.
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!
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
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”.
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.
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?
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.
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?
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?
Источник