# 2021-01-15 #「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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值