通过userAgent切换访问地址的3种方法

1,723 阅读1分钟

现实中经常会碰到根据游览器或者设备,或者系统去访问不同的网页。再此,我总结了3种常用的方法,供大家参考。

第一种:通过JS

var ua = window.userAgent || navigator.userAgent;
if(ua.toLowerCase().indexOf('android')>=0){
    window.location.href="https://google.com"
}else if(ua.toLocaleLowerCase().indexOf("iphone") >= 0){
    window.location.href="https://apple.com"
}else if(ua.toLocaleLowerCase().indexOf("mac") >= 0){
    //此处省略
}

建议将改js放置head标签中,以便尽快执行。

第二种:通过nginx配置

server {
       listen 80;
       listen       443 ssl;
        ssl_certificate /opt/certs/vip/vip_bundle.crt;
	ssl_certificate_key /opt/certs/vip/vip.key;
       server_name www.vip.vip vip.vip;
       access_log  logs/vip_access.log  main;
       error_log   logs/vip_error.log;
       location / {
          root /opt/wwwroot/app;
          try_files $uri $uri.html $uri/ =404;
          index index.html index.htm;
       }
       # 这里就是根据userAgent去判断
       location /geek {
         if ($http_user_agent ~* "Android") {
            root /opt/wwwroot/app/andorid;
            break ;
	      }
         if ($http_user_agent ~* "(iPhone|iPad)") {
            root /opt/wwwroot/app/ios;
            break ;
	      }
         rewrite ^/(.*) https://geek.vip redirect;
       }
}

第三种 通过后台路由

这里是因为我要做一个下载链接,当安卓时直接返回apk,当ios时则返回appstore的地址,我使用了express

app.get('/api/xz',(req, res) => {
    let userAgent=req.headers['user-agent']
    //判断是否是搜索引擎爬虫访问
    if(isRobot(userAgent)){
        res.status(200)
        return
    }else{
        let key=req.query.key||'vip'
        let json=JSON.parse(fs.readFileSync(path.join(__dirname,'./redirectList.json'))),
        switchInfo={},exists=false
        for(let k of json){
            if(k.key===key){
                switchInfo=k
                exists=true
            }
        }
        if(!exists){ 
            res.status(404)
            return
        }
        
        let system=userSystem(userAgent)
        res.redirect(switchInfo[system])
    }
})
//判断是否是搜索引擎
function isRobot(userAgent){
    let RobotList='qihoobot|Baiduspider|Googlebot|Googlebot-Mobile|Googlebot-Image|Mediapartners-Google|Adsbot-Google|Feedfetcher-Google|Yahoo! Slurp|Yahoo! Slurp China|YoudaoBot|Sosospider|Sogou spider|Sogou web spider|MSNBot|ia_archiver|Tomato Bot|FeedDemon|JikeSpider|Indy Library|Alexa Toolbar|AskTbFXTV|AhrefsBot|CrawlDaddy|CoolpadWebkit|Java|Feedly|UniversalFeedParser|ApacheBench|Microsoft URL Control|Swiftbot|ZmEu|oBot|jaunty|Python-urllib|lightDeckReports Bot|YYSpider|DigExt|YisouSpider|HttpClient|MJ12bot|heritrix|EasouSpider|Ezooms'
    return RobotList.split('|').every(k=>{
        return userAgent.indexOf(k)>-1
    })
}
//判断用户系统类型
function userSystem(userAgent){
   let ua=userAgent.toLowerCase()
   if(ua.indexOf('android')>=0){
       return 'android'
   }else if(ua.indexOf('ios')>=0||ua.indexOf('ipad')>=0||ua.indexOf('mac')>=0){
        return 'ios'
   }else{
       return 'other'
   }
}