1. 前言

如果使用宝塔面板需编译安装nginx openresty+nginx-geoip2

2. openresty 安装GeoIP2 Lua库

yum install  -y perl-Digest-MD5

3.opm安装lua api

opm get anjia0532/lua-resty-maxminddb

4. 编写lua脚本

ngx.say("<br>IP location query result:<hr><br>")

local cjson=require 'cjson'
local geo=require 'resty.maxminddb'
local arg_ip=ngx.var.arg_ip
local arg_node=ngx.var.arg_node
ngx.say("IP:",arg_ip,", node:",arg_node,"<br>")

if not geo.initted() then
        geo.init("/data/softwares/GeoIP//GeoLite2-City.mmdb")
end


local res,err=geo.lookup(arg_ip or ngx.var.remote_addr)

if not res then
    ngx.say("Please check the ip address you provided: <div style='color:red'>",arg_ip,"</div>")
    ngx.log(ngx.ERR,' failed to lookup by ip , reason :',err)
else
    ngx.say("Result:",cjson.encode(res))
        if arg_node then
        ngx.say("node name:",ngx.var.arg_node, " , value:",cjson.encode(res[ngx.var.arg_node] or {}))
        end 
end

5. nginx 虚拟主机配置

server {
    listen 80;
    server_name localhost;

    access_log /data/logs/nginx/status.access.log main2;
    error_log /data/logs/nginx/status.error.log error;

    # 获取geoip
    location / {
                default_type "text/html";
            charset utf-8;
                content_by_lua_file /data/conf/nginx/lua/geoip.lua;
    }

    location /myip {
        default_type "text/html";
        charset utf-8;
        content_by_lua_file /data/conf/nginx/lua/getip.lua;
    }
}

6. 测试

image.png

点赞(0)

评论列表 共有 0 评论

暂无评论

微信服务号

微信客服

淘宝店铺

support@elephdev.com

发表
评论
Go
顶部