技术文章 | nginx lua 小项目:根据 user_agent 显示不同的页面_附带和 php 性能的对比

本文来源于阿里云-云栖社区,原文点击这里


怎么快速学习一门新的语言呢?
如果你已经熟练掌握了一门语言,那么其他语言都是想通的。一个小小的需求,可能会遇到很多问题,但是搜索相关的关键字,就能快速实现出来,完成一个小目标,事半功倍。
死记硬背手册,太枯燥了,反正我是看不下去,不如直接来个小项目。

 一个小需求

pc、mobile 一个地址有两套页面,需要在后端根据浏览器的 user_agent 来显示不同的页面。
通过 php 来做,当然可以,但是活动页面访问量一般都比较大,想优化些,所以想尝试下 lua。


 nginx 安装 lua-nginx-module

可以直接上 openresty,不过有时候就是想折腾。
安装的步骤  http://click.aliyun.com/m/31035/ (如果你想实践的话再看吧)


 lua demo 脚本

-- 判断是否是手机浏览器
function isMobile(userAgent)
    -- 99% 前三个都能匹配上吧
    local mobile = {
        "phone", "android", "mobile", "itouch", "ipod", "symbian", "htc", "palmos", "blackberry", "opera mini", "windows ce", "nokia", "fennec",
        "hiptop", "kindle", "mot", "webos", "samsung", "sonyericsson", "wap", "avantgo", "eudoraweb", "minimo", "netfront", "teleca"
    }
    userAgent = string.lower(userAgent)

    for i, v in ipairs(mobile) do
        if string.match(userAgent, v) then
            return true
        end
    end

    return false
end

-- 根据id + 浏览器类型展示活动页面
function showPromotionHtml(id, isMobile)
    local path = "/data/www/mengkang/demo/promotion/"
    local filename

    if isMobile then
        path = path .. "mobile"
    else
        path = path .. "pc"
    end

    filename = path .. "/" .. id .. ".html"

    if file_exists(filename) then
        local file = io.open(filename,"r")
        io.input(file)
        print(io.read("*a"))
        io.close(file)
    else
        print("文件不存在: " .. string.gsub(filename, "/data/www/mengkang/demo", ""))
    end
end

-- 判断文件是否存在
function file_exists(path)
    local file = io.open(path, "rb")
    if file then file:close() end
    return file ~= nil
end

local id = 1
local userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36"
showPromotionHtml(id, isMobile(userAgent))

 小结

作为一个 lua 菜鸟,通过这个小需求我查了哪些资料。

 展开全文

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值