Nginx访问控制

作者:行癫(盗版必究) ------ ## 一:基于IP的访问控制 #### 1.语法格式 ```shell Syntax:allow address | CIDR | unix: | all; default:默认无 Context:http,server,location,limit_except Syntax:deny address | CIDR | unix: | all; default:默认无 Context:http,server,location,limit_except ``` #### 2.案例 ```shell server { listen 80; server_name localhost; location ~ ^/admin { root /home/www/html; index index.html index.hml; deny 192.168.1.8; allow all; } } ``` 注意: ​ 如果先允许访问,在定义拒绝访问;那么拒绝访问不生效 ​ 虚拟机宿主机IP为192.168.1.8,虚拟机IP为192.168.1.11,故这里禁止宿主机访问,允许其他所有IP访问。 宿主机访问http://192.168.1.11/admin,显示403 Forbidden。 当然也可以反向配置,同时也可以使用IP网段的配置方式,如allow 192.168.1.0/24;,表示满足此网段的IP都可以访问 ```shell server { listen 80; server_name localhost; location /foo.html { root /home/www/html; deny all; } } ``` 注意: ​ 如果你想拒绝某个指定URL地址的所有请求,而不是仅仅对其限速,只需要在location块中配置deny all指令 ## 二:基于用户的信任登录 #### 1.语法格式 ```shell Syntax:auth_basic string | off; default:auth_basic off; Context:http,server,location,limit_except Syntax:auth_basic_user_file file; default:默认无 Context:http,server,location,limit_except file:存储用户名密码信息的文件 ``` #### 2.案例 ```shell 配置auth_mod.conf,内容如下: server { listen 80; server_name localhost; location ~ ^/admin { root /home/www/html; index index.html index.hml; auth_basic "Auth access test!"; auth_basic_user_file /etc/nginx/auth_conf; } } auth_basic不为off,开启登录验证功能,auth_basic_user_file加载账号密码文件。 建立口令文件 [root@192 ~]# yum install -y httpd-tools #htpasswd 是开源 http 服务器 apache httpd 的一个命令工具,用于生成 http 基本认证的密码文件 [root@192 ~]# htpasswd -cm /etc/nginx/auth_conf user10 [root@192 ~]# htpasswd -m /etc/nginx/auth_conf user20 [root@192 ~]# cat /etc/nginx/auth_conf user10:$apr1$MOa9UVqF$RlYRMk7eprViEpNtDV0n40 user20:$apr1$biHJhW03$xboNUJgHME6yDd17gkQNb0 注意(参数解释): -c Create a new file. -m Force MD5 encryption of the password (default). ``` ![image-20230509224545431](https://xingdian-image.oss-cn-beijing.aliyuncs.com/xingdian-image/image-20230509224545431.png) #### 3.局限性 ​ 用户信息依赖文件方式 ​ 操作管理机械,效率低下 #### 4.解决方法 ​ Nginx只做中间代理,具体认证交给应用