Nginx+Geoip2实现地区限制

Administrator 5 2023-03-22

Nginx+Geoip2实现地区限制

1.geoip2编译环境

yum -y install gcc zlib zlib-devel pcre-devel openssl openssl-devel geoip-devel

2.下载geoip2模块

ngx_http_geoip2_module-master.zip

3.nginx重新编译添加geoip2模块

查看原编译参数

nginx -V

到nginx编译安装目录下 复制原编译参数 并添加新增模块geoip2路径

./configure --prefix=/usr/local/nginx --add-module=path/to/you-path

编译 #不要make install 不然会重新安装

make

进入objs文件夹复制nginx启动文件至/usr/local/nginx/sbin/nginx

cd objs/
cp objs/nginx /usr/local/nginx/sbin/nginx

重新创建快捷命令
cp /usr/local/nginx/sbin/nginx /usr/sbin/nginx

查看模块是否添加成功使用 /usr/local/nginx/sbin/nginx -V

[root@iZuf647yf0hxjhgxbt7wuiZ sbin]# nginx -V
nginx version: nginx/1.18.0
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC)
configure arguments: --prefix=/usr/local/nginx    --add-module=path/to/you-path

4.配置nginx配置文件添加geoip2数据库

vim nginx.conf

http {
  geoip2 /usr/share/GeoIP/GeoCountry.mmdb {
        $geoip2_country_code country iso_code;
    }

  geoip2 /usr/share/GeoIP/GeoCity.mmdb {
        $geoip2_city_names location time_zone;
    }

  map $geoip2_country_code $allowed_country_test {
        default no;
        RU yes;
    }

server {
        listen       80;
        server_name  localhost;

        add_header country $geoip2_country_code;
        if ( $allowed_country_test = no ) { return 403; }

        location / {
        root   html;
        index  index.html test.htm;
	 }
}

5.平滑重启nginx

nginx -s reload