lua - GeoIP地址库

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

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

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-maxminddb插件

安装libmaxminddb依赖库
下载地址:https://github.com/maxmind/libmaxminddb/releases

安装示例:

wget https://github.com/maxmind/libmaxminddb/releases/download/1.3.2/libmaxminddb-1.3.2.tar.gz
tar zxvf libmaxminddb-1.3.2.tar.gz
cd libmaxminddb-1.3.2
./configure
make && make install
echo /usr/local/lib >> /etc/ld.so.conf.d/local.conf
ldconfig

安装nginx-lua-maxminddb插件

yum -y install perl-Digest-MD5
/usr/local/openresty/bin/opm get anjia0532/lua-resty-maxminddb

IP地址库

wget https://geolite.maxmind.com/download/geoip/database/GeoLite2-City.tar.gz

3 编写lua处理脚本

创建脚本目录

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

获取Geoip地址库
下载地址:https://dev.maxmind.com/geoip/geoip2/geolite2/
下载后的文件名为GeoLite2-City.mmdb,优化建议可以把文件放到/dev/shm之类的内存盘下,提高查询速度

mv GeoLite2-City.mmdb /usr/local/openresty/nginx/lua/
vim /usr/local/openresty/nginx/lua/geoip.lua

local cjson = require 'cjson'
local geo = require 'resty.maxminddb'

if not geo.initted()
then
    geo.init("/usr/local/openresty/nginx/lua/GeoLite2-City.mmdb")
end

--support ipv6 e.g. 2001:4860:0:1001::3004:ef68
local res,err = geo.lookup(ngx.var.arg_ip or ngx.var.remote_addr)

if not res
then
    ngx.log(ngx.ERR,'failed to lookup by ip ,reason:',err)
end

local result = res['country']['names']['zh-CN']

if res['subdivisions']
then
    result = result .. "\t\t" .. res['subdivisions'][1]['names']['zh-CN']
end

if res['city']
then
    result = result .. "\t\t" .. res['city']['names']['zh-CN']
end

ngx.say(result)

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/geoip.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"

上一篇 下一篇

猜你喜欢

热点阅读