第一部分:ip2region准备工作

GitHub 地址:https://github.com/lionsoul2014/ip2region
ip2region - 最自由的ip地址查询库,ip到地区的映射库,提供Binary,B树和纯内存三种查询算法,妈妈再也不用担心我的ip地址定位。

今天的主角是lua_c模块,我们要使用Openresty调用lua查询IP地址定位。

安装Openresty等环境

安装环境套件请移步 https://oneinstack.com/
Openresty安装目录/usr/local/openresty
这里介绍下Openresty采用LuaJit,目前套件中使用的LuaJit2.1对应的Lua5.1版本,固然ip2region的Lua(Ip2region模块的位运算依赖了bit32模块,这个是lua 5.2才开始支持的。)是不能直接使用的。
LuaJit安装目录/usr/local/openresty/luajit/include/luajit-2.1

下载好 GitHub 地址:https://github.com/lionsoul2014/ip2region 源码

编译ip2region.so文件
我们使用到目录binding/lua_c和binding/c目录和ip2region.db文件

将lua_c和c这个目录上传至我们服务器同一个目录,进入lua_c目录,我们要需要修改Makefile

1
2
3
4
5
CC = gcc
LIBS = -I ../c/ -I /usr/local/openresty/luajit/include/luajit-2.1
FFLAGS = -O2 -Wall -fPIC
SO_FILE = Ip2region.so
LIB_DIR = /usr/local/lib/lua/5.1

/usr/local/lib/lua/5.1 为lua存放.so文件。我们要将代码生成到此目录。

第二部分:Openresty调用lua查找ip地址定位

创建lua存放目录及存放db文件

在/usr/local/openresty/nginx/conf目录下创建ip2region文件夹,拷贝我们ip2region.db到此目录
新建我们的主角searcher.lua

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
---
--- Generated by Lua
--- Created by 水郁枫子
--- DateTime: 2020/1/9 23:50
---
ngx.header['Content-Type']="text/plain;charset=UTF-8"


--第一步判断IP是否合法
function checkInvalid()
local headers=ngx.req.get_headers();
local ip=headers["X-REAL-IP"] or headers["X_FORWARDED_FOR"] or ngx.var.remote_addr or "0.0.0.0";
return ip;
end

local ip = checkInvalid();

if ip then
--第二步进行IP定位地址
local Ip2region,err = require "Ip2region";
if not Ip2region then
ngx.log(ngx.ERR,"require Ip2region error: ", err);
ngx.print("require Ip2region error: ", err);
else
local ip2region,err = Ip2region.new("/usr/local/openresty/nginx/conf/ip2region/ip2region.db");
if not ip2region then
ngx.log(ngx.ERR,"require Ip2region error: ", err);
ngx.print("require Ip2region error: ", err);
else
local data,err = ip2region:memorySearch(ip);
if not data then
ngx.print("require Ip2region data error: ", err);
ngx.log(ngx.ERR,"require Ip2region data error: ", err);
else
local region = string.gsub(data.region, "|0", "");
region = string.gsub(region, "0", "");
region = string.gsub(region, "|", "-");
ngx.print(string.format("欢迎你IP:[%s]<br>来自%s的朋友", ip, region));
end
end
end
else
ngx.print("IP address is invalid",ip);
end

Openrsty配置location

假设我们的域名为www.domian.com 那我们修改www.domian.com.conf 文件添加location

1
2
3
4
location /ip { 
default_type 'text/plain';
content_by_lua_file /usr/local/openresty/nginx/conf/ip2region/searcher.lua;
}

测试检验
访问 http://www.domian.com/ip 出现一下内容
欢迎你IP:[119.123.29.173]来自中国-广东省-深圳市-电信的朋友

恭喜您,您已经成功、请尽情享用科技带来喜悦吧。