Apache Traffic Server(ATS) 根据User Agent实现302重定向

    xiaoxiao2021-03-25  94

    需求:通过User Agent判断手机用户,重定向到手机页面。

    首先看github上面的例子,或者直接看官网。 其实很简单,直接来吧

    #判断是否有手机ua关键字的,举了些例子。 function isMobile(userAgent) ua_array = {'android','iphone','ipad','mqqbrowser','windows phone','huawei','htc','meizu','oppo','vivo','xiaomi'} n = table.getn(ua_array) for i= 1, n do if(string.match(userAgent,ua_array[i])) then return true end end return false end #在返回的header里面加入Location,即302之后的地址。 function send_response() if(remap_url) then ts.client_response.header['Location'] = remap_url end return 0 end #判断访问来自手机后返回302 function do_remap() local ua = ts.client_request.header['User-Agent'] if(isMobile(string.lower(ua))) then local uri = ts.client_request.get_uri() if(string.match(uri,'^/$')) then ts.http.set_resp(302) remap_url = "http://wap.test.com/" end end ts.hook(TS_LUA_HOOK_SEND_RESPONSE_HDR, send_response) end

    修改remap.conf配置文件,加一行配置:

    map http://www.test.com/ http://www.test.com/ @plugin=/opt/ts/libexec/trafficserver/tslua.so @pparam=/opt/ts/lib/test.lua

    重新加载配置文件:

    /opt/ts/bin/traffic_ctl config reload

    测试:

    root@zhi:~# curl -v -H "User-Agent:iphone" http://www.test.com/ >/dev/null % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* Trying 192.168.1.6... * Connected to www.gameabc.com (192.168.1.6) port 80 (#0) > GET / HTTP/1.1 > Host: www.gameabc.com > Accept: */* > User-Agent:iphone > < HTTP/1.1 302 Found < Date: Fri, 10 Mar 2017 08:54:15 GMT < Connection: keep-alive < Server: CUWEBCACHE/2.3.4 < Cache-Control: no-store < Content-Type: text/html < Content-Language: en < NODE: HIT < Location: http://wap.test.com/ < Content-Length: 207 < { [207 bytes data] 100 207 100 207 0 0 15572 0 --:--:-- --:--:-- --:--:-- 15923 * Connection #0 to host www.gameabc.com left intact

    完美收工。

    转载请注明原文地址: https://ju.6miu.com/read-23065.html

    最新回复(0)