Nginx白名单IP限制、国家城市IP访问限制

文章来源:https://spring4all.com/forum-post/6059.html

1. 方法一:allow、deny

deny和allow指令属于ngx_http_access_module,nginx默认加载此模块,所以可直接使用。这种方式,最简单,最直接。设置类似防火墙iptable,使用方法:
直接配置文件中添加:

#白名单设置,allow后面为可访问IP 
location / {
     allow 123.13.123.12;
     allow 23.53.32.1/100;
     deny  all;
}

#黑名单设置,deny后面接限制的IP,为什么不加allow all? 因为这个默认是开启的 
location / {
     deny 123.13.123.12;
}

#白名单,特定目录访问限制
location /tree/list {
     allow 123.13.123.12;
     deny  all;
}

可以将这些配置抽到一个配置文件中,优化配置如下

location /{
    include /home/whitelist.conf;
    #默认位置路径为/etc/nginx/ 下,
    #如直接写include whitelist.conf,则只需要在/etc/nginx目录下创建whitelist.conf
    deny all;
}

whitelist.conf,并写入需要加入白名单的IP,添加完成后配置如下

#白名单IP
allow 10.1.1.10;
allow 10.1.1.11;

2. 方法二:ngx_http_geo_module

默认情况下,一般nginx是有加该模块的,ngx_http_geo_module,参数需设置在位置在http模块中。
此模块可设置IP限制,也可设置国家地区限制。位置在server模块外即可。语法示例:

geo $ip_list {
    default 0;
    #设置默认值为0
    192.168.1.0/24 1;
    10.1.0.0/16    1;
}
server {
   listen       8081;
   server_name  192.168.152.100;
   location / {
       root   /var/www/test;
       index  index.html index.htm index.php;
       if ( $ip_list = 0 ) {
       #判断默认值,如果值为0,可访问,这时上面添加的IP为黑名单。
       #白名单,将设置$ip_list = 1,这时上面添加的IP为白名单。
       proxy_pass http://192.168.152.100:8081;
}

同样可通过读取文件IP配置

geo $ip_list {
    default 0;
    #设置默认值为0
    include ip_white.conf;
}
server {
    listen       8081;
    server_name  192.168.152.100;
  
    location / {
        root   /var/www/test;
  index  index.html index.htm index.php;
  if ( $ip_list = 0 ) {
   return 403;
   #限制的IP返回值为403,也可以设置为503,504其他值。
   #建议设置503,504这样返回的页面不会暴露nginx相关信息,限制的IP看到的信息只显示服务器错误,无法判断真正原因。
    }

ip_list.conf 配置如下

192.168.152.1 1;
192.168.150.0/24 1;

设置完成,ip_list.conf的IP为白名单,不在名单中的,直接返回403页面。黑名单设置方法相同。

3. 方法三:ngx_http_geo_module 负载均衡(扩展)

ngx_http_geo_module,模块还可以做负载均衡使用,如web集群在不同地区都有服务器,某个地区IP段,负载均衡至访问某个地区的服务器。方式类似,IP后面加上自定义值,不仅仅数字,如US,CN等字母。

如果三台服务器:122.11.11.11,133.11.12.22,144.11.11.33

geo $country {
    default default;
    111.11.11.0/24   uk;
    #IP段定义值uk
    111.11.12.0/24   us;
    #IP段定义值us
    }
upstream  uk.server {
    erver 122.11.11.11:9090;
    #定义值uk的IP直接访问此服务器
} 

upstream  us.server {
    server 133.11.12.22:9090;
    #定义值us的IP直接访问此服务器
}

upstream  default.server {
    server 144.11.11.33:9090;
    #默认的定义值default的IP直接访问此服务器
}
 
server {
    listen    9090;
    server_name 144.11.11.33;

    location / {
      root  /var/www/html/;
      index index.html index.htm;
     }
 }
posted @ 2024-02-07 20:28  God-slayer  阅读(30)  评论(0编辑  收藏  举报