lua - ipip地址库

2020-06-02  本文已影响0人  路破格

目前仅支持IPv4地址查询,返回国家、省份、城市,不包含运营商

1、安装openresty

下载地址:http://openresty.org/cn/

安装示例:

wget https://openresty.org/download/openresty-1.15.8.3.tar.gz
tar zxvf openresty-1.15.8.3.tar.gz
cd openresty-1.15.8.3
./configure --prefix=/usr/local/openresty
gmake && gmake install

2、安装nginx-lua-ipdb扩展

下载地址:https://github.com/ipipdotnet/ipdb-luajit

安装示例:

wget https://github.com/ipipdotnet/ipdb-luajit/archive/master.zip
unzip master.zip
mv ipdb-luajit-master/resty/ipdb /usr/local/openresty/lualib/resty/

3 编写lua处理脚本

创建脚本目录

mkdir /usr/local/openresty/nginx/lua/

获取ipip试用版ipv4地址库:
下载地址:https://www.ipip.net/product/client.html
下载后的文件名为ipipfree.ipdb,优化建议可以把文件放到/dev/shm之类的内存盘下,提高查询速度

mv ipipfree.ipdb /usr/local/openresty/nginx/lua/
vim /usr/local/openresty/nginx/lua/ip.lua

local city = require 'resty.ipdb.city'
ipdb = city:new("/usr/local/openresty/nginx/lua/ipipfree.ipdb")
local ip = ngx.var.arg_ip

if ip
then
    local loc = ipdb:find(ip, "CN");
    -- 根据需要输出分隔符,本例使用\t\t分割字段,country_name为国家名,region_name为省份名,city_name为城市名
    ngx.say(loc.country_name .. "\t\t" .. loc.region_name .. "\t\t" .. loc.city_name);
else
    ngx.say("error")
end

5 配置nginx

vim /usr/local/openresty/nginx/conf.d/ip.conf

server {
    listen 80;
    server_name your_server_name;

    location / {
        default_type "text/html";
        charset utf-8;
        content_by_lua_file lua/ip.lua;
    }

    access_log off;
}

6 启动nginx

/usr/local/openresty/nginx/sbin/nginx -t && /usr/local/openresty/nginx/sbin/nginx

7 测试验证

curl "http://127.0.0.1/?ip=223.5.5.5"

上一篇 下一篇

猜你喜欢

热点阅读