黑/白名单IP限制访问配置
第一种: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; }# 或者通过读取文件IP配置白名单,在/home/目录下创建whitelist.conf,并写入需要加入白名单的IP,添加完成后查看如下: location /{include /home/whitelist.conf;#默认位置路径为/etc/nginx/ 下,#如直接写include whitelist.conf,则只需要在/etc/nginx目录下创建whitelist.confdeny all; }cat /home/whitelist.conf #白名单IP allow 10.1.1.10; allow 10.1.1.11;
第二种方法,ngx_http_geo_module,参数需设置在位置在http模块中。此模块可设置IP限制,也可设置国家地区限制。位置在server模块外即可
# 配置文件直接添加 geo $ip_list {default 0;#设置默认值为0192.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;#设置默认值为0include 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看到的信息只显示服务器错误,无法判断真正原因。} }cat /etc/nginx/ip_list.conf 192.168.152.1 1; 192.168.150.0/24 1;
ngx_http_geo_module 负载均衡(扩展) ngx_http_geo_module,模块还可以做负载均衡使用,如web集群在不同地区都有服务器,某个地区IP段,负载均衡至访问某个地区的服务器。方式类似,IP后面加上自定义值,不仅仅数字,如US,CN等字母。
geo $country {default default;111.11.11.0/24 uk;#IP段定义值uk111.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;}}