IP2Location Nginx Module 配置使用小结 - V2EX
V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
请不要在回答技术问题时复制粘贴 AI 生成的内容
wsgzao
V2EX    程序员

IP2Location Nginx Module 配置使用小结

  •  
  •   wsgzao
    wsgzao 2020-04-21 17:58:11 +08:00 2526 次点击
    这是一个创建于 2056 天前的主题,其中的信息可能已经有所发展或是发生改变。

    前言

    IP2Location 主要是用于代替 MaxMind GeoIP,原因是 GeoIP 数据库针对中国的 Blacklist 黑名单有非常高的误伤率,选择 IP2Location 可以有效降低误伤,为了业务需求得及时做出改变。在使用 IP2Location 的过程中发现官网的步骤还是存在一些问题,这里记录和分享下自己逐步解决问题的过程。

    更新历史

    2020 年 04 月 21 日 - 初稿

    阅读原文 - https://wsgzao.github.io/post/ip2location/


    GeoIP 和 IP2Location 简介

    GeoIP是一套含 IP 数据库的软件工具。除此之外还有IP2Location等,国内做得比较深入的是高春辉创建的IPIP.NET

    Geo 根据来访者的 IP, 定位该 IP 所在经纬度、国家 /地区、省市、和街道等位置信息。

    GeoIP/IP2Location 等通常有两个版本,一个免费版,一个收费版本。

    收费版本的准确率高一些,更新频率也更频繁。

    Geo IP solution to identify country, region, city, latitude & longitude, ZIP code, time zone, connection speed, ISP, domain name, IDD country code, area code, weather station data, mobile network codes (MNC), mobile country codes (MCC), mobile carrier, elevation and usage type.

    GeoIP 是大家都非常熟悉的老字号,而这次的主角是 IP2Location

    IP2Location Nginx Module

    This is an IP2Location Nginx Module that enables the user to identify the country code and country name by IP address. In general, it is faster, easier and more accurate than reverse DNS lookups.

    https://www.ip2location.com/development-libraries/ip2location/nginx

    Installation

    IP2Location C library enables the user to find the country, region, city, coordinates, ZIP code, time zone, ISP, domain name, connection type, area code, weather, MCC, MNC, mobile brand name, elevation and usage type that any IP address or hostname originates from. It has been optimized for speed and memory utilization. Developers can use the API to query all IP2Location binary databases for IPv4 and IPv6 address.

    • Download IP2location C library from here.

    • Download and decompress this Nginx module package.

    • Change the path to IP2Location library in "ngx_http_ip2location_module.c".

    • Re-compile Nginx from source to include this module. Add the below directive into the compile of Nginx:

      ./configure --add-module=/absolute/path/to/nginx-ip2location-8.0.0 make make install

    • Edit your Nginx config file to point the correct path of IP2Location database file:

      ip2location_database /absolute/path/to/IP2LOCATION-DB1.BIN;

    安装备注

    IP2Location 官方的执行步骤存在一些问题没有说清楚,这里分享自己实践后的步骤和结论

    安装依赖包

    # These are for RedHat, CentOS, and Fedora. sudo yum install wget git gcc-c++ pcre-devel zlib-devel make libtool autoconf automake # These are for Debian. Ubuntu will be similar. sudo apt-get install wget git build-essential zlib1g-dev libpcre3 libpcre3-dev libtool autoconf automake 

    编译 IP2Location C library

    git clone https://github.com/chrislim2888/IP2Location-C-Library cd IP2Location-C-Library autoreconf -i -v --force ./configure make make install # 以下步骤可选 cd data perl ip-country.pl cd ../test ./test-IP2Location 

    编译 Nginx

    nginx: download

    # Download ip2location-nginx git clone https://github.com/ip2location/ip2location-nginx # IP2Location library in "ngx_http_ip2location_module.c" cd ip2location-nginx vim ngx_http_ip2location_module.c #include "IP2Location.h" #include "/root/ip2location/IP2Location-C-Library-master/libIP2Location/IP2Location.h" # Download Nginx Stable version VERSION="1.16.1" wget http://nginx.org/download/nginx-${VERSION}.tar.gz tar -xvzf nginx-${VERSION}.tar.gz cd nginx-${VERSION} # Compile Nginx ./configure --add-module=../ip2location-nginx make sudo make install # error: Failed dependencies: # libIP2Location.so.1()(64bit) is needed by nginx-garena-1.16.1-0.noarch # 一般编译 nginx 二进制文件不会出现该问题,如果你使用 rpmbuild 打包就要注意了 rpm -Uvh https://rpms.remirepo.net/enterprise/7/remi/x86_64/libip2location-8.0.7-1.el7.remi.x86_64.rpm 

    IP2Location Database Download

    IP2Location offers 5 free LITE databases and 24 commercial IP geolocation databases. Free database is less accurate comparing to commercial database.

    # Create new directory for IP2Location database. mkdir -p /usr/share/ip2location cd /usr/share/ip2location # Go to https://lite.ip2location.com. Sign up an account for login and password. # Download and decompress the latest IP2Location LITE database. wget http://download.ip2location.com/lite/IP2LOCATION-LITE-DB1.BIN.ZIP unzip IP2LOCATION-LITE-DB1.BIN.ZIP 

    Configuration

    You need to configure Nginx to use IP2LOCATION module.

    # Edit vi /etc/nginx/nginx.conf # Add following lines under `http` context: http { ip2location on; ip2location_database /usr/share/ip2location/IP2LOCATION-LITE-DB1.BIN; #ip2location_database /usr/share/ip2location/IP-COUNTRY-REGION-CITY-LATITUDE-LONGITUDE-ZIPCODE-ISP-DOMAIN.BIN ip2location_access_type shared_memory; } 

    可选参数 ip2location_access_type file_io|shared_memory|cache_memory 默认为 shared_memory 建议不要选择 file_io, 否则可能会严重拖慢响应速度

    Syntax

    Syntax:ip2location on|off Default: off Context: http, server, location Description: Enable or disable IP2LOCATION Nginx module.

    Syntax:ip2location_database path Default: none Context: http Description: The absolute path to IP2LOCATION BIN database.

    Syntax:ip2location_access_type file_io|shared_memory|cache_memory Default: shared_memory Context: http Description: Set the method used for lookup.

    Syntax:ip2location_proxy cidr|address Default: none Context: http Description: Set a list of proxies to translate x-forwarded-for headers for.

    Syntax:ip2location_proxy_recursive on|off Default: off Context: http Description: Enable recursive search in the x-forwarded-for headers.

    Variables

    The following variables will be made available in Nginx:

    ip2location_country_short ip2location_country_long ip2location_region ip2location_city ip2location_isp ip2location_latitude ip2location_longitude ip2location_domain ip2location_zipcode ip2location_timezone ip2location_netspeed ip2location_iddcode ip2location_areacode ip2location_weatherstationcode ip2location_weatherstationname ip2location_mcc ip2location_mnc ip2location_elevation ip2location_usagetype 

    You may block the traffic from United States in Nginx as below:

    if ( $ip2location_country_short = 'US' ) { return 444; } if ( $ip2location_country_short = 'SG' ) { return 444; } 

    还可以参照 GeoIP 的配置方法

    map $ip2location_country_short $blacklist_country { default no; CN yes; } server { listen 80; server_name wangao.com; if ($blacklist_country = yes) { return 444; } 

    浏览器访问检查 nginx log 结果

    tailf /var/log/nginx/access.log xxx - - [21/Apr/2020:17:18:11 +0800] "GET / HTTP/1.1" 200 396 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36" xxx - - [21/Apr/2020:17:18:42 +0800] "GET / HTTP/1.1" 444 0 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36" 

    IP2Location Python Library

    This module is a Python Library to support all IP2Location database products. It has been optimized for speed and memory utilization. Developers can use this API to query all IP2Location binary databases for IPv4 and IPv6 address.

    https://www.ip2location.com/development-libraries/ip2location/python

    import IP2Location IP2LocObj = IP2Location.IP2Location() ''' Cache the database into memory to accelerate lookup speed. WARNING: Please make sure your system have sufficient RAM to use this feature. ''' # database = IP2Location.IP2Location(os.path.join("data", "IPV6-COUNTRY.BIN"), "SHARED_MEMORY") IP2LocObj.open("data/IP-COUNTRY-REGION-CITY-LATITUDE-LONGITUDE-ZIPCODE-TIMEZONE-ISP-DOMAIN-NETSPEED-AREACODE-WEATHER-MOBILE-ELEVATION-USAGETYPE-SAMPLE.BIN") rec = IP2LocObj.get_all("19.5.10.1") print rec.country_short 
    import IP2Location import sys import argparse def ip2location_search(ip, db): IP2LocObj = IP2Location.IP2Location() ''' Cache the database into memory to accelerate lookup speed. WARNING: Please make sure your system have sufficient RAM to use this feature. ''' # database = IP2Location.IP2Location(os.path.join("data", "IPV6-COUNTRY.BIN"), "SHARED_MEMORY") IP2LocObj.open(db) rec = IP2LocObj.get_all(ip) print rec.country_short def _parse_args(): parser = argparse.ArgumentParser(description="Search IP in IP2Location Database") parser.add_argument("-i", "--ip", help="Input ip", required=True) parser.add_argument("-d", "--db", help="Path to ip2location db", required=True) return parser.parse_args() if __name__ == "__main__": args = _parse_args() ip = args.ip db = args.db ip2location_search(ip, db) 

    参考文章

    How to use IP2Location GeoLocation with Nginx

    How to Install IP2Location Nginx Module on Debian

    Upgrade to GeoIP2 with NGINX on CentOS/RHEL

    4 条回复    2020-09-01 16:14:01 +08:00
    royan
        1
    royan  
       2020-04-21 18:08:33 +08:00
    不错,支持!
    aveline
        2
    aveline  
       2020-04-22 07:07:41 +08:00   1
    如果只是过滤中国 IP,可以试试我们的 chnroutes2,每小时定时从路由上抓的数据:
    https://github.com/misakaio/chnroutes2

    IP2Location 的准确度非常差,而且经常瞎猜地址,比如说 WHOIS 里我们的以前注册地址是美国 DE 的 New Castle,他们会标成 OK 的 Castle,我们俄罗斯的 IP 也经常会被标在 LA 。沟通很累,如果不是这个用途个人还是建议继续用 GeoIP 或者 ipinfo 。IPIP 目前的更新速度是全球最快的,准确率也不错,只是价格很贵。
    wsgzao
        3
    wsgzao  
    OP
       2020-04-22 10:02:57 +08:00
    @aveline #2
    谢谢这么详细的专业回复,GeoIP 和 IP2Location 商业版都采购了但发现后者误伤低,之前一直使用 GeoIP,因为原本的作用其实并不是过滤中国,而是要做游戏运营上的细分,跨国做一些黑白名单机制。因为第一次使用 IP2Location,发现官网和 Google 搜索出来的文章在配置介绍上都比较模糊,于是就分享了这篇简单的文章。不过还是非常感谢你的回复,给我们提供了新的解决思路。
    alamak76
        4
    alamak76  
       2020-09-01 6:14:01 +08:00
    谢谢。IP2Location 蛮好用。
    关于     帮助文档     自助推广系统     博客     API     FAQ     Solana     5935 人在线   最高记录 6679       Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 27ms UTC 02:38 PVG 10:38 LAX 18:38 JFK 21:38
    Do have faith in what you're doing.
    ubao msn snddm index pchome yahoo rakuten mypaper meadowduck bidyahoo youbao zxmzxm asda bnvcg cvbfg dfscv mmhjk xxddc yybgb zznbn ccubao uaitu acv GXCV ET GDG YH FG BCVB FJFH CBRE CBC GDG ET54 WRWR RWER WREW WRWER RWER SDG EW SF DSFSF fbbs ubao fhd dfg ewr dg df ewwr ewwr et ruyut utut dfg fgd gdfgt etg dfgt dfgd ert4 gd fgg wr 235 wer3 we vsdf sdf gdf ert xcv sdf rwer hfd dfg cvb rwf afb dfh jgh bmn lgh rty gfds cxv xcv xcs vdas fdf fgd cv sdf tert sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf shasha9178 shasha9178 shasha9178 shasha9178 shasha9178 liflif2 liflif2 liflif2 liflif2 liflif2 liblib3 liblib3 liblib3 liblib3 liblib3 zhazha444 zhazha444 zhazha444 zhazha444 zhazha444 dende5 dende denden denden2 denden21 fenfen9 fenf619 fen619 fenfe9 fe619 sdf sdf sdf sdf sdf zhazh90 zhazh0 zhaa50 zha90 zh590 zho zhoz zhozh zhozho zhozho2 lislis lls95 lili95 lils5 liss9 sdf0ty987 sdft876 sdft9876 sdf09876 sd0t9876 sdf0ty98 sdf0976 sdf0ty986 sdf0ty96 sdf0t76 sdf0876 df0ty98 sf0t876 sd0ty76 sdy76 sdf76 sdf0t76 sdf0ty9 sdf0ty98 sdf0ty987 sdf0ty98 sdf6676 sdf876 sd876 sd876 sdf6 sdf6 sdf9876 sdf0t sdf06 sdf0ty9776 sdf0ty9776 sdf0ty76 sdf8876 sdf0t sd6 sdf06 s688876 sd688 sdf86