有三种方法:
第1种:使用淘宝或者其他ip转换地址,可以转换, 准确,但是请求频率限制了。 第2种:使用lua读取本地文件ip库,这种需要使用二叉树算法读取文件,获取位置。 速度会有些慢,对服务器压力大,准确。 第3中: 使用第三方ip转换库 ip2region 的git地址 https://gitee.com/lionsoul/ip2region/ ip2region 这个库暂时不兼容nginx-lua版本的解析,但是可以单独使用lua解析位置,需要引入bit32模块,这个是lua-5.2之后才支持,nginx-lua有默认的低版本的lua,暂时无法升级版本。 这种方法速度快,频率低。中国的 maxminddb 这个库是外国的第三方ip库,有收费版本和免费版本的库,免费版本ip解析不太准确,速度快。步骤稍麻烦 maxminddb 介绍地址 https://blog.csdn.net/reblue520/article/details/100549432 maxminddb兼容nginx-lua方法 1.下载压缩包 libmaxminddb-1.4.3 地址 下方 国内下载git地址 https://gitee.com/freeasm/libmaxminddb?_from=gitee_search 2.下载ip解析库 网盘分享地址: 库的地址 链接:https://pan.baidu.com/s/1s4HdS3sxAdFAUpJuev9F7g 提取码:238f 复制这段内容后打开百度网盘手机App,操作更方便哦 3.下载解析api文件 git里边有介绍 下载 maxminddb.lua https://github.com/anjia0532/lua-resty-maxminddb 4.所有下载完毕之后上传到服务器。 5.将解析库 GeoLite2-City-放到自己的lualib目录中,将maxminddb.lua文件上传道lualib/resty中,后面需要引入这两个文件,所以权限要给够。 6.libmaxminddb-1.4.3解压后,进入 cd libmaxminddb-1.3.2 ./configure make make check make install ldconfig 默认情况下上述操作会将libmaxminddb.so部署到/usr/local/lib目录下,为了让openresty访问,可以拷贝到openresty目录下,或通过如下步骤更新ldconfig。 sh -c "echo /usr/local/lib >> /etc/ld.so.conf.d/local.conf" ldconfig 7.编写lua代码进行访问 8.http://106.52.148.123:8072/test?ip=106.52.148.123&node=city 访问
libmaxminddb-1.4.3 国外下载地址:
lua代码
local args = ngx.req.get_uri_args();
local cjson = require 'cjson'
local geo = require 'resty.maxminddb'
if not geo.initted() then geo.init("/www/server/nginx/lualib/GeoLite2-City.mmdb")
end
local res,err = geo.lookup(args["ip"])
if not res then
ngx.log(ngx.ERR,'failed to lookup by ip ,reason:',err)
end
ngx.say("full :",cjson.encode(res))
if ngx.var.arg_node then
ngx.say("node name:",ngx.var.arg_node," ,value:", cjson.encode(res[ngx.var.arg_node] or {}))
end