Nginx配置限制地区访问

##安裝GeoIP相依套件

cd /opt/src
wget https://github.com/maxmind/libmaxminddb/releases/download/1.6.0/libmaxminddb-1.6.0.tar.gz
tar -zxvf libmaxminddb-1.6.0.tar.gz
cd libmaxminddb-1.6.0
./configure
make
make check
make install
ldconfig
sudo sh -c "echo /usr/local/lib >> /etc/ld.so.conf.d/local.conf"
ldconfig
ls /usr/local/lib

##備份之前的文件

cp /usr/local/openresty/nginx/conf/nginx.conf /usr/local/openresty/nginx/conf/nginx.conf.bak
cp /usr/local/openresty/nginx/sbin/nginx /usr/local/openresty/nginx/sbin/nginx.bak

cd /opt/src
wget https://yw-du.oss-accelerate.aliyuncs.com/Geoip_new.tar.gz
#wget ftp://106.12.106.146/pub/Geoip_new.tar.gz
tar zxvf Geoip_new.tar.gz

複製GeoIP資料庫**

cd /opt/src/Geoip_new
cp GeoLite2-Country.mmdb /usr/local/openresty/

複製GeoIP模組**

mkdir -p /usr/local/openresty/nginx/modules/
cd /opt/src/Geoip_new
cp ngx_http_geoip2_module.so /usr/local/openresty/nginx/modules/
cp ngx_stream_geoip2_module.so /usr/local/openresty/nginx/modules/

每个conf文件添加限制,TW表示为限制台湾地区,CN为中国大陆。

sed -i "s/ location \/ {/ if (\$geoip2_data_country_code ~ (TW)) { return 511; } location \/ {/g" /usr/local/openresty/nginx/conf/vhost/*.conf
cd /usr/local/openresty/nginx/sbin/
./nginx -t
./nginx -s reload
cd /opt/src/Geoip_new
mv ./nginx /usr/local/openresty/nginx/sbin/nginx //替换nginx版本
cd /usr/local/openresty/nginx/sbin/
./nginx -s stop && ./nginx

猜你喜欢

转载自blog.csdn.net/weixin_42324463/article/details/121444682