纯 Nginx 打造 IP 地址查询接口

基于 Maxmind DBNginx 实现的IP信息查询接口,完全使用 Nginx 模块实现,不依赖其他第三方动态语言或SDK。

此项目使用了免费版 Maxmind DB 数据,归属地可能不够精确。读者可自行更换更好的兼容库。

快速安装方法

docker run -d -p 80:80 -p 443:443 rehiy/geoip-api

启动后,浏览器访问 http://your-ip/help 即可查看帮助页面

手动安装方法

安装http-echohttp_geoip2模块

配置IP库

geoip2 /usr/share/geoip/city-lite.mmdb {
    auto_reload 5m;
    $geoip2_data_country_code country iso_code;
    $geoip2_data_country_name country names en;
    $geoip2_data_province_name subdivisions 0 names en;
    $geoip2_data_city_name city names en;
    $geoip2_data_location_latitude location latitude;
    $geoip2_data_location_longitude location longitude;
}

配置站点

server {

    listen 80;
    listen [::]:80;

    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    ssl_certificate certs/default.cer;
    ssl_certificate_key certs/default.key;

    server_name ipip.rehiy.com ipv4.rehiy.com ipv6.rehiy.com;

    default_type text/plain;

    location / {
        if ($http_user_agent ~* "curl|wget") {
            rewrite / /ip last;
        }
        rewrite / /info last;
    }

    location /ip {
        echo $remote_addr;
    }
    location /country_code {
        echo $geoip2_data_country_code;
    }
    location /country {
        echo $geoip2_data_country_name;
    }
    location /province {
        echo $geoip2_data_province_name;
    }
    location /city {
        echo $geoip2_data_city_name;
    }
    location /latitude {
        echo $geoip2_data_location_latitude;
    }
    location /longitude {
        echo $geoip2_data_location_longitude;
    }
    location /ua {
        echo $http_user_agent;
    }

    location /info {
        echo "IP ADDRESS   : $remote_addr";
        echo " ";
        echo "COUNTRY CODE : $geoip2_data_country_code";
        echo "COUNTRY      : $geoip2_data_country_name";
        echo "PROVINCE     : $geoip2_data_province_name";
        echo "CITY         : $geoip2_data_city_name";
        echo " ";
        echo "LATITUDE     : $geoip2_data_location_latitude";
        echo "LONGITUDE    : $geoip2_data_location_longitude";
        echo " ";
        echo "USER AGENT   : $http_user_agent";
    }

    location /help {
        echo "/              IP INFO (browser) | IP ADDRESS (wget/curl)";
        echo " ";
        echo "/ip            IP ADDRESS";
        echo " ";
        echo "/country_code  COUNTRY CODE";
        echo "/country       COUNTRY NAME";
        echo "/province      PROVINCE NAME";
        echo "/city          CITY NAME";
        echo " ";
        echo "/latitude      LATITUDE";
        echo "/longitude     LONGITUDE";
        echo " ";
        echo "/ua            USER AGENT";
    }

}
最后修改于:2022年11月18日 12:25

添加新评论