nginx地域拦截 ip地址分配
- 2018-11-04 21:27:00
- admin
- 原创 81
一、nginx地域拦截
1、maxmind免费数据库:https://github.com/P3TERX/GeoLite.mmdb
2、maxmind工具:https://github.com/maxmind/mmdbinspect
3、maxmind依赖:https://github.com/maxmind/libmaxminddb
4、maxmind依赖:https://github.com/maxmind/MaxMind-DB-Reader-python
5、geoip2插件:https://github.com/leev/ngx_http_geoip2_module
6、安装依赖:pip install maxminddb
编译libmaxminddb:
cd libmaxminddb-1.13.3
./configure --prefix=/data/mylib/libmaxminddb --enable-static --disable-shared
make && make install
编译nginx:
./configure --with-stream \
--add-module=/data/mylib/ngx_http_geoip2_module-3.4 \
--with-cc-opt="-I/data/mylib/libmaxminddb/include" \
--with-ld-opt="-L/data/mylib/libmaxminddb/lib -lmaxminddb" \
--prefix=/data/mylib/nginx-1.20.2
make && make install
二、nginx地域拦截的配置
geo $in_white_list {
default 0;
include /data/mylib/nginx-1.20.2/cn_ips.conf;
}
geoip2 /data/mylib/maxmind/GeoLite2-Country.mmdb {
auto_reload 5m;
$geoip2_country_code_raw country iso_code;
}
map $geoip2_country_code_raw $geoip2_country_code {
"" "NEW_IP";
default $geoip2_country_code_raw;
}
map $geoip2_country_code $allowed_country {
default 0; # 默认拦截
CN 1; # 允许中国
NEW_IP 1; # 允许新增
}
map $in_white_list$allowed_country $allow_request {
default 0;
"11" 1;
"10" 1;
"01" 1;
"00" 0;
}
if ($allow_request != 1) {
return 403 "Access denied for your region";
}
三、nginx地域拦截的日志
map "" $fmt_part1 {
default "[$time_iso8601] $msec $remote_addr";
}
map "" $fmt_part2 {
default "$in_white_list $geoip2_country_code [$allow_request]";
}
map "" $fmt_part3 {
default "[$request] $request_length $bytes_sent $status";
}
log_format geo_log "${fmt_part1} ${fmt_part2} ${fmt_part3}";
access_log /data/mylib/nginx-1.20.2/geo_access.log geo_log;
四、ip地址分配
1、IANA,互联网号码分配机构,全球只有一个;
2、RIR,区域互联网注册管理机构,全球一共五个;
3、IANA全局分配情况:https://www.iana.org/numbers
4、RIR详细分配记录:https://ftp.apnic.net/stats/apnic