> For the complete documentation index, see [llms.txt](https://yangsx95.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://yangsx95.gitbook.io/notes/distributed/web-fu-wu-qi/nginx/fang-wen-kong-zhi.md).

# 访问控制

## http\_access\_module

基于IP的访问控制

```nginx
# 允许哪些 ip(address)、网段(CIDR)、socket方式(unix:)、所有(all) 可以访问
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
```

示例：

```nginx
#限制我的ip不可访问，其他所有的都可以访问
#被限制的ip会显示 403 Forbidden
location ! ^/admin.html {
    root /usr/share/nginx/html;
    deny 140.207.236.xxx;
    allow all;
}

#只允许以下网段访问，其他一概不允许访问
location ! ^/admin.html {
    root /usr/share/nginx/html;
    allow 182.168.173.0/24;
    deny all;
}
```

### 局限性

如果客户端经过代理访问nginx服务端，如下图：

![1556021378338](/files/QwKOYsd53vwNpSrHrZRZ)

因为access\_module是根据 `$remote_addr`来进行限制的，那么对于Nginx来说，此时`$remote_addr`就是IP2，那么nginx对IP1的限制就失效了。这就是局限性。

针对这种问题共有以下几种方式：

* http\_x\_forwarded\_for
* 结合geo模块
* 通过HTTP自定义变量传递

### http\_x\_forwarded\_for

![1556021634871](/files/DvcfmnKZED9fhSfLfTG3)

x\_forwoared\_for 会带着真正的客户端的ip(即图中的IP1)给nginx。

```
http_x_forwarded_for = ClientIP,Proxy1_IP,Proxy2_IP ...
# x_forwarded_for不仅包含ClientIP，还包含中间的代理ip
```

**缺点：**

* http\_x\_forwarded\_for 是基于协议的，不一定所有的厂商都支持，而且又被修改的可能性

## http\_auth\_basic\_module

基于用户的信任登录进行访问控制

```nginx
# 开启认证，string代表开启，off代表关闭，string可以是任意值，一般是提示语
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
```

示例：

```shell
# 生成密码文件
# htpasswd -c /etc/nginx/auth_conf 用户名
# 期间需要手动输入面膜
htpasswd -c /etc/nginx/auth_conf admin
New password: 
Re-type new password: 
Adding password for user admin

# 查看文件
[root@localhost html]# cat /etc/nginx/auth_conf 
admin:$apr1$Kjg/tGgG$US4oklegzqMq7QITWoaj/0

# 配置nginx配置
location ~ ^/admin.html {
	root /usr/share/nginx/html;
	auth_basic "Please input your password!";
	auth_basic_user_file /etc/nginx/auth_conf;
}
```

配置成功后，访问 `ip:port/admin.html`，会弹出如下认证提示：

![1556023343240](/files/2w7fgnPakirxpqXWgJD3)

### 局限性

* 用户信息需要存储在文件中，依赖文件
* 操作机械、管理低效

**对应的解决方案：**

* nginx结合LUA实现高效验证
* nginx配合LDAP打通，利用`nginx-auth-ldap`模块
