如果你用nginx,那么可以尝试在nginx配置中写:
server {
server_name **.**; #你的网站
listen 443;
ssl on;
ssl_certificate /usr/local/nginx/conf/server.crt;
ssl_certificate_key /usr/local/nginx/conf/server_nopwd.key;
location / {
if ($http_user_agent ~ "((MIDP)|(WAP)|(UP.Browser)|(Smartphone)|(Obigo)|(Mobile)|(AU.Browser)|(wxd.Mms)|(WxdB.Browser)|(CLDC)|(UP.Link)|(KM.Browser)|(UCWEB)|(SEMC\-Browser)|(Mini)|(Symbian)|(Palm)|(Nokia)|(Panasonic)|(MOT)|(SonyEricsson)|(NEC)|(Alcatel)|(Ericsson)|(BENQ)|(BenQ)|(Amoisonic)|(Amoi)|(Capitel)|(PHILIPS)|(SAMSUNG)|(Lenovo)|(Mitsu)|(Motorola)|(SHARP)|(WAPPER)|(LG)|(EG900)|(CECT)|(Compal)|(kejian)|(Bird)|(BIRD)|(G900/V1.0)|(Arima)|(CTL)|(TDG)|(Daxian)|(DAXIAN)|(DBTEL)|(Eastcom)|(EASTCOM)|(PANTECH)|(Dopod)|(Haier)|(HAIER)|(KONKA)|(KEJIAN)|(LENOVO)|(Soutec)|(SOUTEC)|(SAGEM)|(SEC)|(SED)|(EMOL)|(INNO55)|(ZTE)|(iPhone)|(Android)|(Windows CE)|(Wget)|(Java)|(curl)|(Opera))"){
rewrite ^/(.*)$ http://**。**/$1 ;
}
}
server{
server_name **.**;
listen 80;
location /{
if ($http_user_agent ~ "常见桌面UA"){
rewrite ^/(.*)$ https://**。**/$1 ;
}
}
}
如果你网站有入口文件index.php,那么在入口文件中写会更加简单:
以下是https的入口文件,http的入口文件请讲逻辑反转即可。
<?php
$the_host = $_SERVER['HTTP_HOST'];//取得当前域名
$the_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';//判断地址后面部分
if(is_mobile_user_agent()//判断UA是否手机浏览器或者PC浏览器。此函数的实现自己去百度搜
{
header('HTTP/1.1 301 Moved Permanently');
header('Location:http://**.**'.$the_url); //
}
?>
写个插件,PHP 判断 UA 对手机端进行跳转。
最简单的方法在入口页面做判断
可以像www.qq.com那样在页面<head>里用JS进行重定向:
<head>
<script type="text/javascript">
if(window.location.toString().indexOf('pref=padindex') != -1){
}else{
if(/AppleWebKit.*Mobile/i.test(navigator.userAgent) || (/MIDP|SymbianOS|NOKIA|SAMSUNG|LG|NEC|TCL|Alcatel|BIRD|DBTEL|Dopod|PHILIPS|HAIER|LENOVO|MOT-|Nokia|SonyEricsson|SIE-|Amoi|ZTE/.test(navigator.userAgent))){
if(window.location.href.indexOf("?mobile")<0){
try{
if(/Android|Windows Phone|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)){
window.location.href="http://xw.qq.com/index.htm";
}else if(/iPad/i.test(navigator.userAgent)){
window.location.href="http://www.qq.com/pad/"
}else{
window.location.href="http://xw.qq.com/simple/s/index/"
}
}catch(e){}
}
}
}
</script>
</head>
这个之前面试的时候被问到一个这样的问题,相同的uri如何区分客户端。
第一种就是一楼的方法,通过nginx判别然后重定向url。
第二种就是PHP对客户端的判断。比如在CI框架中,可以在入口文件对客户端进行检测然后通过路由获取客户端对应的资源。