使用HTTP基本认证限制访问
简介
可以通过用户名/口令认证限制访问整个网站或部分区域。用户名和口令来自由口令文件创建工具(例如apache2-utils)创建并填充的文件。
HTTP基本认证还可以与其他访问限制组合,例如按IP地址或地理位置限制。
前置条件
- F5 NGINX Plus或NGINX开源版。
- 口令文件创建工具,例如Debian/Ubuntu的
apache2-utils,或RHEL/CentOS/Oracle Linux的httpd-tools。
创建口令文件
使用apache2-utils或httpd-tools等工具创建用户名与口令对。
1. 确认相应口令工具已经安装。
2. 创建口令文件及首个用户。运行htpasswd,使用创建文件的-c标志,第一个参数为文件路径,第二个参数为用户名:
sudo htpasswd -c /etc/apache2/.htpasswd user1
按Enter,并在提示中输入user1的口令。
3. 创建更多用户与口令对。由于文件已存在,省略-c:
sudo htpasswd /etc/apache2/.htpasswd user2
4. 可以确认文件包含用户名及对应口令哈希:
$ cat /etc/apache2/.htpasswd
user1:<HASHED_PASSWORD>
user2:<HASHED_PASSWORD>
user3:<HASHED_PASSWORD>
为NGINX与NGINX Plus配置HTTP基本认证
1. 在需要保护的location内指定auth_basic指令,并为口令保护区域命名。请求凭据时,该名称会显示在用户名/口令对话框中:
location /api {
auth_basic "Administrator’s Area";
#...
}
2. 使用auth_basic_user_file指令指定包含用户名/口令对的.htpasswd文件路径:
location /api {
auth_basic "Administrator’s Area";
auth_basic_user_file /etc/apache2/.htpasswd;
}
也可以对整个网站启用基本认证,同时让部分区域保持公开。此时设置auth_basic的off参数,取消从上层配置继承的认证:
server {
...
auth_basic "Administrator’s Area";
auth_basic_user_file conf/htpasswd;
location /public/ {
auth_basic off;
}
}
将基本认证与IP地址限制组合
HTTP基本认证可有效结合按IP地址进行的访问限制,可实现至少两种情形:
- 用户必须同时通过认证并来自允许的IP地址。
- 用户只需通过认证,或者来自允许的IP地址。
1. 通过allow与deny指令允许或拒绝特定IP地址:
location /api {
#...
deny 192.168.1.2;
allow 192.168.1.1/24;
allow 127.0.0.1;
deny all;
}
只允许192.168.1.1/24网络访问,但排除192.168.1.2。allow和deny按定义顺序执行。
2. 用satisfy指令组合IP限制与HTTP认证。设为all时,客户端必须同时满足两个条件;设为any时,只要满足至少一个条件即可:
location /api {
#...
satisfy all;
deny 192.168.1.2;
allow 192.168.1.1/24;
allow 127.0.0.1;
deny all;
auth_basic "Administrator’s Area";
auth_basic_user_file conf/htpasswd;
}
完整示例
以下示例通过简单认证结合IP地址限制,保护状态区域:
http {
server {
listen 192.168.1.23:8080;
root /usr/share/nginx/html;
location /api {
api;
satisfy all;
deny 192.168.1.2;
allow 192.168.1.1/24;
allow 127.0.0.1;
deny all;
auth_basic "Administrator’s Area";
auth_basic_user_file /etc/apache2/.htpasswd;
}
}
}
访问状态页时,系统会提示登录。
如果提供的用户名和口令与口令文件不匹配,将得到401 (Authorization Required)错误。
原文:Restricting Access with HTTP Basic Authentication,NGINX官方文档。© 2026 F5, Inc. All rights reserved. NGINX是F5, Inc.的注册商标。按转载授权汉化。完整示例中的api;指令按原文保留,其适用产品范围应参照NGINX Plus文档。











暂无评论内容