Nginx   发布时间:2022-05-11  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了「Nginx」- 配置基本认证(Basic Authentication) @20210217大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

问题描述

配置 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

参考文献

NGINX Docs | Restricting Access with HTTP Basic Authentication
HTTP Basic Authentication - what's the expected web browser experience? - Stack Overflow

大佬总结

以上是大佬教程为你收集整理的「Nginx」- 配置基本认证(Basic Authentication) @20210217全部内容,希望文章能够帮你解决「Nginx」- 配置基本认证(Basic Authentication) @20210217所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: