# 2021-01-14 #「Nginx」- 配置基本认证(Basic Authentication)

问题描述

配置 Nginx 基础认证(Basic Authentication),实现在访问站点时提示用户进行基础认证。

解决方法

第一步、添加用户

// 创建新的 .htpasswd 文件

# htpasswd -c /etc/apache2/.htpasswd "tom"
New password: 
Re-type new password: 
Adding password for user tom

// 追加用户到 .htpasswd 文件

# htpasswd /etc/apache2/.htpasswd "cat"
New password: 
Re-type new password: 
Adding password for user cat

// 验证添加成功

# cat /etc/apache2/.htpasswd
tom:$apr1$jf5bsAhN$/5nLq.A726iSqNWiAqdZ5/
cat:$apr1$qUV52OEi$vz0mUy6kXLrWcMh1aI3nD/

第二步、修改 Nginx 配置

server {
    ...
    auth_basic              "Administrator’s Area";
    auth_basic_user_file    /etc/apache2/.htpasswd;

    location /public/ {
        auth_basic off; # 在该地址下,关闭认证
    }
    ...
}

第三步、配置生效并验证

# systemctl reload nginx.service
# curl --user username:password http://example.com

常见问题汇总

在修改 Basic Auth 信息后,是否需要重启

Does auth_basic changes require a service reload? - Server / NGINX - Ruby-Forum

添加或者修改 Basic Auth 信息,无需进行 Nginx 重启,该文件是运行时加载的。

为某个网络地址禁用基本认证

Module ngx_http_core_module / satisfy
Module ngx_http_access_module
web server - How to disable http basic auth in nginx for a specific ip range? - Server Fault

server {
    ...
    satisfy any; 
    
    # ngx_http_access_module
    allow <our ip address>;
    deny all;
    
    # ngx_http_auth_basic_module
    auth_basic              "Administrator’s Area";
    auth_basic_user_file    /etc/apache2/.htpasswd;
    ...
}

解释说明:配置 satisfy any; 表示只要通过 ngx_http_access_module, ngx_http_auth_basic_module, ngx_http_auth_request_module, ngx_http_auth_jwt_module 模块中的某个模块的检查,则允许进行访问。如上配置:我们的网络地址,通过 ngx_http_access_module 检查,允许访问;其他的网络地址,受到 ngx_http_access_module 限制,但是只要通过 ngx_http_auth_basic_module 的认证,依旧可以访问。

如何使用明文密码(不建议)

Module ngx_http_auth_basic_module/auth_basic_user_file
RFC 2307 - An Approach for Using LDAP as a Network Information Service

虽然不建议,但是依旧有方法:

username:{PLAIN}your-password

参考文献

WikiNotes/配置基本认证(Basic Authentication)
NGINX Docs | Restricting Access with HTTP Basic Authentication
HTTP Basic Authentication - what's the expected web browser experience? - Stack Overflow


posted @ 2021-01-14 16:35  研究林纳斯写的  阅读(214)  评论(0编辑  收藏  举报