在HTTP中,基本认证(Basic access authentication)是一种用来允许网页浏览器或其他客户端程序在请求时提供用户名和口令形式的身份凭证的一种登录验证方式。

常见的用户认证截图

ngx_http_auth_basic_module模块实现让访问着,只有输入正确的用户密码才允许访问web内容。web上的一些内容不想被其他人知道,但是又想让部分人看到。Nginx的http auth模块以及Apache http auth都是很好的解决方案。

默认情况下Nginx已经安装了ngx_http_auth_basic_module模块,如果不需要这个模块,可以加上 --without-http_auth_basic_module

Nginx Basic HTTP authentication

Nginx的用户配置实例

location / {
    auth_basic           "my site";
    auth_basic_user_file conf/htpasswd;
}

指令说明

auth_basic

  • 语法: auth_basic string | off;
  • 默认值: auth_basic off;
  • 上下文: http,server,location,limit_except

开启使用“HTTP基本认证”(HTTP Basic Authentication)协议的用户名密码验证。指定的参数被用作域。参数可以包含变量。参数off可以取消继承自上一个配置等级auth_basic指令的影响。参数off表示不开启HTTP基本认证。

另外auth_basic指定的字符串会在弹窗中显示。

auth_basic_user_file

  • 语法: auth_basic_user_file file;
  • 默认值: —
  • 上下文: http,server,location,limit_except

指定保存用户名密码的文件。
参数file中可以包含变量。

保存用户名和密码的文件格式如下:

# comment
name1:password1
name2:password2:comment
name3:password3

密码应该使用crypt()函数加密。可以用Apache HTTP Server发行包中的htpasswd命令或者openssl passwd来创建此类文件。

参数file可以是文件、相对路径的文件、绝对路径的文件。非绝对路径下,文件的位置是相对于nginx安装路径下的conf目录的。比如nginx的安装路径是/usr/local/nginx,则设置对应的路径举例说明如下:

auth_basic_user_file htpasswd;
# htpasswd在机器上的位置:/usr/local/nginx/conf/htpasswd
auth_basic_user_file conf/htpasswd;
# htpasswd在机器上的位置:/usr/local/nginx/conf/conf/htpasswd
auth_basic_user_file /tmp/htpasswd;
# htpasswd在机器上的位置:/tmp/htpasswd

创建用户名为admin,密码为12345的示例如下:

htpasswd

[root@test ~]# /opt/apache/bin/htpasswd -bdc htpasswd admin 12345
Adding password for user admin
[root@test ~]# cat htpasswd
admin:PbSRr7orsxaso

openssl passwd

[root@test ~]# openssl passwd 12345
fIHcRVEKijgoM
[root@test ~]# echo "admin:fIHcRVEKijgoM" > htpasswd
[root@test ~]# cat htpasswd
admin:fIHcRVEKijgoM

当然也可以使用Web在线htpasswd生成器来生产用户名和密码字符串复制粘贴到文件中保存引用。

变量说明

$remote_user

为HTTP基本认证提供的用户名。例如上述示例中提到的用户admin。

在Nginx里给你的站点或者目录加个用户认证

最后修改:2022 年 07 月 01 日
如果觉得我的文章对你有用,请随意赞赏