nginx/第八章:Nginx访问控制.md

111 lines
3.0 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<h1><center>Nginx访问控制</center></h1>
作者:行癫(盗版必究)
------
## 一基于IP的访问控制
#### 1.语法格式
```shell
Syntaxallow address | CIDR | unix: | all;
default默认无
Contexthttpserverlocationlimit_except
Syntaxdeny address | CIDR | unix: | all;
default默认无
Contexthttpserverlocationlimit_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
Syntaxauth_basic string | off;
defaultauth_basic off;
Contexthttpserverlocationlimit_except
Syntaxauth_basic_user_file file;
default默认无
Contexthttpserverlocationlimit_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只做中间代理具体认证交给应用