简体   繁体   中英

How to redirect mobile site users to a mobile layout

I can't find some solid information on what I'm specifically looking for, nor do I know the best method of doing this (in code or using HTACCESS); to redirect mobile users to http://m.example.com

I am looking to enable both mobile, and PC users to view our website in both devices, with a user-friendly layout to accommodate for both users.

The solution without HTACCESS:

Best way is store the info about which layout is selected in Cookie.

if(isset($_GET["setMobile"])) {
  setcookie("m", $_GET["setMobile"], time()+(60*60*24*31), "/");
}

And then

if($_COOKIE["m"]) {
  /* MOBILE LAYOUT */
}

I thnk you do not even Need htaccess. You can create index.php in your subfolder m.domain.com and place there Cookie Definition.

setcookie("m", true, time()+(60*60*24*31), "/");

Solution: A : To redirect mobile users to mobile layout

Via .htaccess

RewriteEngine On
RewriteCond %{QUERY_STRING} !^desktop
RewriteCond %{HTTP_USER_AGENT} "android|blackberry|googlebot-mobile|iemobile|iphone|ipod|#opera mobile|palmos|webos" [NC]
RewriteRule ^$ http://m.example.com [L,R=302]

=====================

Solution: B: Redirect mobile site users to mobile layout and from mobile to desktop

Via PHP Session

<a href="<?php echo $_SERVER['PHP_SELF'], '?desktop=1' ?>">Go to Desktop version</a>

<?php
if(!isset($_SESSION['desktop'])) {
    $_SESSION['desktop'] = false;
}

if(isset($_GET['desktop']) && $_GET['desktop'] == 1) {
    $_SESSION['desktop'] = true;
}

if(!$_SESSION['desktop']) {
    if ( !$detect->isMobile() ) {
      header('Location: http://m.example.com/');
    }
}
?>

On your mobile site, you can pass a get parameter of desktop=1. Normally, if the parameter is not passed, and if the session is not set, it's false. On false value of $_SESSION['desktop'], you continue your script so it redirects to mobile. But once the param is passed, it changes the session to true, and you block will not be executed, so the normal (desktop) content of the site will be visible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM