nginx使用GeoIP限制国家访问

时间:2022-05-05
本文章向大家介绍nginx使用GeoIP限制国家访问,主要内容包括安装GEeoip库、安装openresty(Nginx)、测试访问效果、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

安装GEeoip库

安装完成之后,GeoIP数据库会被安装在/usr/share/GeoIP/GeoIP.dat.

[root@vultr ~]# yum -y install geoip-devel
[root@vultr openresty-1.13.6.1]# ls /usr/share/GeoIP/GeoIP.dat
/usr/share/GeoIP/GeoIP.dat

安装openresty(Nginx)

[root@vultr openresty-1.13.6.1]# ./configure --user=www --group=www --prefix=/usr/local --with-http_stub_status_module --with-http_ssl_module --with-http_v2_module --with-http_gzip_static_module --with-ipv6 --with-http_sub_module --with-http_geoip_module
[root@vultr openresty-1.13.6.1]# make && make install
<pre lang="bash" line="1" escaped="true">
 
<h2><strong>配置openresty支持Geoip</strong></h2>
<pre lang="bash" line="1" escaped="true">
[root@vultr openresty-1.13.6.1]# vim /usr/local/nginx/conf/nginx.conf
....
http {
geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $allowed_country {
default yes;
US no; # 国家 no就是不允许哪个国际访问
}
....
server{
....
        if ($allowed_country = no) { # 添加判断,如果访问国家=no,就返回404
                return 404;
        }
...
}
[root@vultr openresty-1.13.6.1]# /usr/local/nginx/sbin/nginx -t  # 检测nginx配置文件
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@vultr openresty-1.13.6.1]# /usr/local/nginx/sbin/nginx # 启动nginx

测试访问效果

本地ip地址江苏苏州移动

访问提示404,和预期的效果一样。

参考文献: [1]:https://www.vpsee.com/2011/03/install-nginx-with-geoip-module-for-country-targeting/ [2]:http://www.dnsdizhi.com/post-175.html [3]:http://blog.angryfox.com/?p=1688