nginx屏蔽或者限制某些国家或者地区的访问请求

首先要安装这个模块地址

https://github.com/maxmind/libmaxminddb

1
2
3
4
5
$ ./configure
$ make
$ make check
$ sudo make install
$ sudo ldconfig

如果在安装后收到错误消息,libmaxminddb.so.0您可能需要将lib目录添加prefix到您的库路径中。在大多数使用默认前缀 ( /usr/local) 的 Linux 发行版上,您可以通过运行以下命令来执行此操作:

1
2
$ sudo sh -c "echo /usr/local/lib  >> /etc/ld.so.conf.d/local.conf"
$ ldconfig

模块地址 https://github.com/leev/ngx_http_geoip2_module

下载nginx源码包,1.9版本以上

1
2
3
wget http://nginx.org/download/nginx-VERSION.tar.gz
tar zxvf nginx-VERSION.tar.gz
cd nginx-VERSION

编译Nginx并添加模块

1
2
3
./configure --add-dynamic-module=/path/to/ngx_http_geoip2_module
make
make install

如果需要stream支持,请确保使用stream进行编译:

1
2
3
./configure --add-dynamic-module=/path/to/ngx_http_geoip2_module --with-stream
OR
./configure --add-module=/path/to/ngx_http_geoip2_module --with-stream

在nginx.conf添加配置,注意要放在stream和http前面

1
2
load_module /www/server/nginx/modules/ngx_http_geoip2_module.so;
load_module /www/server/nginx/modules/ngx_stream_geoip2_module.so;

stream里面配置

1
2
3
4
5
6
7
stream {
......
geoip2 /www/server/geoip/GeoLite2-Country.mmdb {
$geoip2_data_country_code default=US source=$remote_addr country iso_code;
}
......
}

配置nginx.conf stream限制某些国家或者地区

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
stream {
......
upstream prod_backend {
server 127.0.0.1:22;
}

upstream test_backend {
server 127.0.0.1:2222;
}

map $geoip2_data_country_code $backend_svr {
CN "prod_backend";
default "test_backend";
}
server{
listen 9022;
proxy_pass $backend_svr;
}
......
}

配置nginx.conf http限制某些国家

1
2
3
4
5
6
7
http {
......
geoip2 /www/server/geoip/GeoLite2-Country.mmdb {
$geoip2_country_code default=- source=$remote_addr country iso_code;
}
......
}

主机文件配置里面添加

1
2
3
4
5
6
7
server {
......
if ($geoip2_country_code !~ CN) {
return 403;
}
......
}