經過userAgent切換訪問地址的3種方法

現實中常常會碰到根據遊覽器或者設備,或者系統去訪問不一樣的網頁。再此,我總結了3種經常使用的方法,供你們參考。html

第一種:經過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標籤中,以便儘快執行。android

第二種:經過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的地址,我使用了expressios

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'
   }
}
複製代碼
相關文章
相關標籤/搜索