根据地区进行跳转
server {
location / {
lua_code_cache off;
charset utf-8;
rewrite_by_lua '
local ip = ngx.var.remote_addr
local cjson = require "cjson.safe"
local ipdb = ngx.shared.ipdb
local res = "none"
--local ip = ngx.var.ip
_, _, ipa, ipb, ipc, ipd = string.find(ip, "(%d+).(%d+).(%d+).(%d+)")
ipnum = ipa*16777216 + ipb*65536 + ipc*256 + ipd
groupId = tonumber(ipa)
ipGroup = cjson.decode(ipdb:get("group:"..groupId))
groupTot = table.getn(ipGroup)
for i = 1, groupTot do
if (ipnum >= ipGroup[i][1]) and (ipnum <= ipGroup[i][2]) then
res = ipGroup[i][3]
break
end
end
--ngx.print(res)
local diqu = string.sub(res,2,7)
--local i, j = string.find(res, "局域")
if not( diqu == "安徽" or diqu == "江苏" or diqu == "浙江" ) then
return ngx.redirect("http://www.goodid.com")
end
--ngx.print(i,j)
';
#将ip库加载到内存http://www.yufei.com/setip
location /setip {
default_type 'text/plain';
content_by_lua '
local function run()
local cjson = require "cjson.safe"
local ipdb = ngx.shared.ipdb
local ipTab = {}
for i=0, 255 do
ipTab[i] = {}
end
for item in io.lines("/data/ip.txt") do
local _, _, startIpa, startIpb, startIpc, startIpd = string.find(string.match(string.sub(item, 1, 15),"%s*(.-)%s*$"),"(%d+).(%d+).(%d+).(%d+)")
if startIpa then
local startIpnum = startIpa*16777216 + startIpb*65536 + startIpc*256 + startIpd
_, _, endIpa, endIpb, endIpc, endIpd = string.find(string.match(string.sub(item, 17, 31),"%s*(.-)%s*$"),"(%d+).(%d+).(%d+).(%d+)")
endIpnum = endIpa*16777216 + endIpb*65536 + endIpc*256 + endIpd
table.insert(ipTab[tonumber(startIpa or 0)],{startIpnum, endIpnum, string.sub(item, 32, 200)})
end
end
for i=0, 255 do
local setInfo = cjson.encode(ipTab[i])
ipdb:set("group:"..i, setInfo)
end
ngx.say("ok")
end
local code,err=pcall(run)
if not code then
ngx.print("error"..err)
ngx.exit(200)
end
';
}
#http://www.yufei.com/getip?ip=114.114.114.114,114.114.114.115,114.114.114.116,批量获取,json格式返回
location /getip {
default_type 'text/plain';
charset utf-8;
content_by_lua '
local args = ngx.req.get_query_args()
local ip = args["ip"]
local phone = args["phone"]
function string.split(self,sep)
self=self or ""
local sep, fields = sep or "\t", {}
local pattern = string.format("([^%s]+)", sep)
string.gsub(self,pattern, function(c) fields[#fields+1] = c end)
return fields
end
local ip_table = string.split(ip, ",")
local res_table = {}
local res = "none"
local cjson = require "cjson"
for i=1,#ip_table do
local ip = ip_table[i]
local cjson = require "cjson.safe"
local ipdb = ngx.shared.ipdb
_, _, ipa, ipb, ipc, ipd = string.find(ip, "(%d+).(%d+).(%d+).(%d+)")
ipnum = ipa*16777216 + ipb*65536 + ipc*256 + ipd
groupId = tonumber(ipa)
ipGroup = cjson.decode(ipdb:get("group:"..groupId))
groupTot = table.getn(ipGroup)
for i = 1, groupTot do
if (ipnum >= ipGroup[i][1]) and (ipnum <= ipGroup[i][2]) then
res = ipGroup[i][3]
break
end
end
table.insert(res_table,res)
--res_table[#res_table+1] = res
end
ngx.print(cjson.encode(res_table))
ngx.exit(200)
ngx_lua尝试做ip库
最新推荐文章于 2024-08-09 04:07:20 发布