NGINX+Lua=parser_ip

Парсинг ip в nginx на лету по maxmind базе

apt install openresty-opm libmaxminddb-dev
opm get anjia0532/lua-resty-maxminddb
nginx.conf
  location /somemagicurl {
    expires max;
    content_by_lua_block {
    local cjson = require 'cjson'
    local geo = require 'resty.maxminddb'
    if not geo.initted() then
      geo.init("/geoip/GeoIP2-City.mmdb")
    end
    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
    if ngx.var.arg_node == nil then
      ngx.header["Content-Type"] = "application/json"
      ngx.say(cjson.encode(res))
      ngx.exit(0)
    else
      ngx.header["Content-Type"] = "application/json"
      ngx.say(cjson.encode(res[ngx.var.arg_node] or {}))
      ngx.exit(0)
    end
    }
  }

http://127.0.0.0.1/somemagicurl/

or

http://127.0.0.0.1/somemagicurl/?ip=8.8.8.8

or

http://127.0.0.0.1/somemagicurl/?ip=8.8.8.8&node=country

Last updated