根据用户代理

时间:2019-02-13 13:40:13

标签: php wordpress nginx

我试图用nginx以及wordpress index.php中的php标头重定向来实现这一点,但是我总是发现自己陷入了无限循环。

我只想将iphone用户重定向到我的wordpress页面的/ category / iphone /或将android用户重定向到/ category / android/。

这可能吗?

谢谢您的帮助!

编辑: 也许我不是很清楚。如果用户进入INDEX / MAIN页面,我只想对其进行重定向。他仍然可以浏览其他类别,而无需将他重定向到iphone / android类别。

1 个答案:

答案 0 :(得分:2)

此if陈述将使您能够使用以下其中一种检测出iOS和移动设备访问者:

if( stristr($_SERVER['HTTP_USER_AGENT'],'ipad') ) {
        $device = "ipad";
    } else if( stristr($_SERVER['HTTP_USER_AGENT'],'iphone') || strstr($_SERVER['HTTP_USER_AGENT'],'iphone') ) {
        $device = "iphone";
    } else if( stristr($_SERVER['HTTP_USER_AGENT'],'blackberry') ) {
        $device = "blackberry";
    } else if( stristr($_SERVER['HTTP_USER_AGENT'],'android') ) {
        $device = "android";
    }

    if( $device ) {
        return $device; 
    } return false; {
        return false;
    }
}

即使您可以使用.htaccess文件,例如:

RewriteCond %{HTTP_USER_AGENT} ^.*Android.*$
RewriteRule ^(.*)$ http://www.yoururl.com [R=301]

在functions.php文件中:

    add_action( 'template_redirect', 'device_redirect' );

    function device_redirect(){
      if ( is_front_page() && is_home() ) {
        if( stristr($_SERVER['HTTP_USER_AGENT'],'iphone') || strstr($_SERVER['HTTP_USER_AGENT'],'iphone') ) {
                wp_redirect( "http://www.example.com/iphone", 301 );
        } else if( stristr($_SERVER['HTTP_USER_AGENT'],'android') ) {
               wp_redirect( "http://www.example.com/andriod", 301 );
        }
     }
   }

如果使用静态主页或博客页面,则必须更改if。 例如

if ( is_front_page() && is_home() ) {
// Default homepage
}

if ( is_front_page()){
//Static homepage
} 

if ( is_home()){
//Blog page
}
相关问题