1 Introduction

If you use the Pagoda panel, you need to compile and install nginx openresty+nginx-geoip2

2. openresty installs the GeoIP2 Lua library

yum install -y perl-Digest-MD5

3.opm install lua api

opm get anjia0532/lua-resty-maxminddb

4. Write lua script

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 virtual host configuration

server {
     listen 80;
     server_name localhost;

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

     # Get 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. Test

image.png

点赞(0)

评论列表 共有 0 评论

暂无评论

微信服务号

微信客服

淘宝店铺

support@elephdev.com

发表
评论
Go
顶部