Rootop 服务器运维与web架构

nginx通过geoip2模块实现判断用户来源国家跳转中英站

ip数据库文件下载地址:https://dev.maxmind.com/geoip/geoip2/geolite2/

编译nginx添加第二代geoip2模块,第一代自带 的–with-http_geoip_module 生命周期算是尾声了。ip地址库都下载不到了。

# 下载独立的geoip2模块,官方nginx还未加入

git clone https://github.com/leev/ngx_http_geoip2_module

# 编译nginx加上geoip2

--add-module=../ngx_http_geoip2_module

报错:
./configure: error: the geoip2 module requires the maxminddb library.
解决:需要安装 libmaxminddb 库,这个是用来读取ip数据文件的。

下载 https://github.com/maxmind/libmaxminddb/releases/download/1.3.2/libmaxminddb-1.3.2.tar.gz
解压依次执行:

./configure
make
make install
echo /usr/local/lib  >> /etc/ld.so.conf.d/local.conf
ldconfig

即可。

重新编译nginx通过。

# 编辑nginx配置文件

http {
    # 只提取关键配置参数
    
    geoip2 /usr/local/GeoLite2-Country_20190507/GeoLite2-Country.mmdb {
        $geoip2_data_country_code default=CN country iso_code;
    }

    server {
        add_header "country" $geoip2_data_country_code; #添加个响应头,方便查。
        
        location / {
            if ($geoip2_data_country_code = CN) {
                root /mnt/cn;
            }
            
            if ($geoip2_data_country_code != CN) {
                root /mnt/other;
            }
        }
    }
}

访问测试,查看响应头中的country字段。

$geoip2_data_country_code 变量是自定义名称的变量,其值是在geoip2解析ip后生成。
default=CN country iso_code 这些参数实际是下面命令返回json的key,default是为了查不到相关key的值时,设置一个默认值。

[root@localhost]# mmdblookup --file GeoLite2-City.mmdb --ip x.x.x.x

原创文章,转载请注明。本文链接地址: https://www.rootop.org/pages/4366.html

作者:Venus

服务器运维与性能优化

评论已关闭。