Nginx根據User-Agent適配PC和手機

考慮到網站的在多種設備下的兼容性,有不少網站會有手機版和電腦版兩個版本。訪問同一個網站URL,當服務端識別出用戶使用電腦訪問,就打開電腦版的頁面,用戶若是使用手機訪問,則會獲得手機版的頁面。html

一、判斷客戶端的設備類型

要想讓網站適配PC和手機設備,首先要能作出準確的判斷。HTTP請求的Header中的User-Agent能夠區分客戶端的瀏覽器類型,能夠經過User-Agent來判斷客戶端的設備。android

不管是PC仍是手機,因爲操做系統、瀏覽器的多樣性,本身來實現這個判斷並不容易。好在國外有一套開源的經過User-Agent區分PC和手機的解決方案,能夠直接使用:web

http://detectmobilebrowsers.com/正則表達式

因爲本文使用Nginx,只要在網站上下載Nginx配置便可。windows

set $mobile_rewrite do_not_perform;

if ($http_user_agent ~* "(androidbb\d+meego).+mobileavantgobada\/blackberryblazercompalelainefennechiptopiemobileip(honeod)iriskindlelge maemomidpmmpmobile.+firefoxnetfrontopera m(obin)ipalm( os)?phonep(ixire)\/pluckerpocketpspseries(46)0symbiantreoup\.(browserlink)vodafonewapwindows cexdaxiino") {
  set $mobile_rewrite perform;
}

if ($http_user_agent ~* "^(1207631065903gso4thp50[1-6]i770s802sa waabacac(eroos\-)ai(korn)al(avcaco)amoian(exnyyw)aptuar(chgo)as(teus)attwau(di\-mr s )avanbe(ckllnq)bi(lbrd)bl(acaz)br(ev)wbumbbw\-(nu)c55\/capiccwacdm\-cellchtmcldccmd\-co(mpnd)crawda(itllng)dbtedc\-sdevidicadmobdo(cp)ods(12\-d)el(49ai)em(l2ul)er(ick0)esl8ez([4-7]0oswaze)fetcfly(\-_)g1 ug560genegf\-5g\-mogo(\.wod)gr(adun)haiehcithd\-(mpt)hei\-hi(ptta)hp( iip)hs\-cht(c(\- _agpst)tp)hu(awtc)i\-(20goma)i230iac( \-\/)ibroideaig01ikomim1kinnoipaqirisja(tv)ajbrojemujigskddikejikgt( \/)klonkpt kwc\-kyo(ck)le(noxi)lg( g\/(klu)5054\-[a-w])libwlynxm1\-wm3gam50\/ma(teuixo)mc(0121ca)m\-crme(rcri)mi(o8oats)mmefmo(0102bidedot(\- ov)zz)mt(50p1v )mwbpmywan10[0-2]n20[2-3]n30(02)n50(025)n7(0(01)10)ne((cm)\-ontfwfwgwt)nok(6i)nzpho2imop(tiwv)oranowg1p800pan(adt)pdxgpg(13\-([1-8]c))philpirepl(ayuc)pn\-2po(ckrtse)proxpsiopt\-gqa\-aqc(0712213260\-[2-7]i\-)qtekr380r600raksrim9ro(vezo)s55\/sa(gemammmsnyva)sc(01h\-oop\-)sdk\/se(c(\-01)47mcndri)sgh\-sharsie(\-m)sk\-0sl(45id)sm(alarb3itt5)so(ftny)sp(01h\-v\-v )sy(01mb)t2(1850)t6(001018)ta(gtlk)tcl\-tdg\-tel(im)tim\-t\-moto(plsh)ts(70m\-m3m5)tx\-9up(\.bg1si)utstv400v750verivi(rgte)vk(405[0-3]\-v)vm40vodavulcvx(52536061708081838598)w3c(\- )webcwhitwi(g ncnw)wmlbwonux700yas\-yourzetozte\-)") {
  set $mobile_rewrite perform;
}

if ($mobile_rewrite = perform) {
  # 手機
}

Nginx經過以上的配置,獲取HTTP請求的User-Agent,使用正則表達式來匹配手機設備。api

二、根據設備適配不一樣的頁面

首先要準備好網站的PC版和手機版兩套頁面,經過以前對設備的判斷,來反向代理到不一樣的版本:瀏覽器

location / {
    proxy_pass http://192.168.20.1;  # 電腦版
    if ($mobile_rewrite = perform) {
        proxy_pass http://192.168.20.2;  # 手機版
    }
}

若是是靜態頁面不須要反向代理,那麼用root替換proxy_pass:cookie

location / {
    root /html/pc;
    if ($mobile_rewrite = perform) {
        root /html/mobile;
    }
}

三、手機版連接到PC版

在用戶打開頁面後,若是進入了手機版,可能因爲錯誤判斷設備,或者用戶想獲取更多信息,可能會須要打開PC版。在手機版頁面的底部,一般會有一個連接指向PC版:ide

能夠經過在點擊「電腦版」連接的時候用JavaScript設置一個Cookie來實現這個功能:oop

<a href="http://xxx.com/" onclick="document.cookie = "gotopc=true"">電腦版</a>

同時在Nginx配置中加入判斷,若是包含此Cookie則進入PC版:

if ($http_cookie ~ "gotopc=true") {
	set $mobile_rewrite do_not_perform;
}

四、調試

完成以上配置後,能夠經過Chrome瀏覽器來模擬手機、平板電腦等設備。

最後給出完整的Nginx配置:

server {  
    listen 80;
    
    set $mobile_rewrite do_not_perform;
    
    if ($http_user_agent ~* "(androidbb\d+meego).+mobileavantgobada\/blackberryblazercompalelainefennechiptopiemobileip(honeod)iriskindlelge maemomidpmmpmobile.+firefoxnetfrontopera m(obin)ipalm( os)?phonep(ixire)\/pluckerpocketpspseries(46)0symbiantreoup\.(browserlink)vodafonewapwindows cexdaxiino") {
        set $mobile_rewrite perform;
    }
    
    if ($http_user_agent ~* "^(1207631065903gso4thp50[1-6]i770s802sa waabacac(eroos\-)ai(korn)al(avcaco)amoian(exnyyw)aptuar(chgo)as(teus)attwau(di\-mr s )avanbe(ckllnq)bi(lbrd)bl(acaz)br(ev)wbumbbw\-(nu)c55\/capiccwacdm\-cellchtmcldccmd\-co(mpnd)crawda(itllng)dbtedc\-sdevidicadmobdo(cp)ods(12\-d)el(49ai)em(l2ul)er(ick0)esl8ez([4-7]0oswaze)fetcfly(\-_)g1 ug560genegf\-5g\-mogo(\.wod)gr(adun)haiehcithd\-(mpt)hei\-hi(ptta)hp( iip)hs\-cht(c(\- _agpst)tp)hu(awtc)i\-(20goma)i230iac( \-\/)ibroideaig01ikomim1kinnoipaqirisja(tv)ajbrojemujigskddikejikgt( \/)klonkpt kwc\-kyo(ck)le(noxi)lg( g\/(klu)5054\-[a-w])libwlynxm1\-wm3gam50\/ma(teuixo)mc(0121ca)m\-crme(rcri)mi(o8oats)mmefmo(0102bidedot(\- ov)zz)mt(50p1v )mwbpmywan10[0-2]n20[2-3]n30(02)n50(025)n7(0(01)10)ne((cm)\-ontfwfwgwt)nok(6i)nzpho2imop(tiwv)oranowg1p800pan(adt)pdxgpg(13\-([1-8]c))philpirepl(ayuc)pn\-2po(ckrtse)proxpsiopt\-gqa\-aqc(0712213260\-[2-7]i\-)qtekr380r600raksrim9ro(vezo)s55\/sa(gemammmsnyva)sc(01h\-oop\-)sdk\/se(c(\-01)47mcndri)sgh\-sharsie(\-m)sk\-0sl(45id)sm(alarb3itt5)so(ftny)sp(01h\-v\-v )sy(01mb)t2(1850)t6(001018)ta(gtlk)tcl\-tdg\-tel(im)tim\-t\-moto(plsh)ts(70m\-m3m5)tx\-9up(\.bg1si)utstv400v750verivi(rgte)vk(405[0-3]\-v)vm40vodavulcvx(52536061708081838598)w3c(\- )webcwhitwi(g ncnw)wmlbwonux700yas\-yourzetozte\-)") {
        set $mobile_rewrite perform;
    }
    
    if ($http_cookie ~ "gotopc=true") {
        set $mobile_rewrite do_not_perform;
    }
    
    location / {
        proxy_pass http://192.168.20.1;  # 電腦版
        if ($mobile_rewrite = perform) {
            proxy_pass http://192.168.20.2;  # 手機版
        }
    }
}
相關文章
相關標籤/搜索