我如何使用 php 或 JavaScript 使一个人被重定向到我的移动网站(如果他们在移动设备上)


How do I use php or JavaScript to make a person be redirected to my mobile site if they are on a mobile?

>我有一个移动网站,但如果用户在移动设备上,我需要一个脚本来重定向到它。

有几种方法可以做到这一点,但检测屏幕尺寸是一个很好的方法。请注意,屏幕宽度与浏览器窗口大小无关。

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

您还可以通过用户代理字符串匹配 iPhone 或 iPod 等特定设备。

<script language=javascript>
<!--
if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {
   location.replace("http://url-to-send-them/iphone.html");
}
-->
</script>

重要警告

虽然这有效,但当您尝试访问特定页面时,被重定向到移动网站的首页也很烦人。例如,当您点击来自Facebook的链接试图访问一篇文章时,如果该网站将您重定向到该网站移动版的首页,那将令人愤怒且非常无益!很有可能,他们永远不会足够努力地找到内容。

paulsm4 是正确的,使用 CSS 在同一 URL 上为您的网站提供移动布局而不是重定向是一个更理想的解决方案。但是,如果这不是一个选项,下一个最好的办法是重定向到网站的移动版本的匹配URL。

例如,如果您的移动网站只有一个不同的子域,那么您可以使用 Javascript 重定向到移动版本的正确页面:

<script type="text/javascript">
<!--
// Full URL:   http://example.com/articles/1
// Mobile URL: http://mobile.example.com/articles/1
if (screen.width <= 699) {
  // Redirect to the same page on the mobile site
  document.location.host = "mobile." + document.location.host;
}
//-->
</script>

您必须先检测浏览器。这是一个页面,其中包含有关使用 javascript 进行浏览器检测的信息: http://www.w3schools.com/js/js_browser.asp如果检测到的浏览器是其中一个移动浏览器,则将它们重定向到另一个页面。这里有一个关于这个主题的非常有用的页面:http://www.zytrax.com/tech/web/mobile_ids.html还包含用于浏览器检测的 PHP 代码

你的第一道防线应该是使用 CSS:

  • http://www.alistapart.com/articles/return-of-the-mobile-stylesheet

  • http://perishablepress.com/the-5-minute-css-mobile-makeover/

除此之外,这里有一些可以为你做重定向的Javascript:

  • http://css-tricks.com/snippets/javascript/redirect-mobile-devices/

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

您不必使用 JS 执行此操作 - 浏览器实际上在 HTTP 标头中将任何内容发送回浏览器之前将代理字符串发送到 PHP。看看$_SERVER['HTTP_USER_AGENT'],你就会明白我的意思。

CodeIgniter 有一个用户代理类,可以帮助处理这种行为。它的源在这里,它与浏览器代理字符串一起使用的资源文件在这里。