Nginx auth basic模块实现简单登录验证

177 阅读1分钟

1.简介

ngx_http_auth_basic_模块允许通过使用“http基本身份验证”协议验证用户名和密码来限制对资源的访问。访问也可以由地址、子请求的结果或JWT限制。通过地址和密码同时限制访问由satisfy指令控制。

2.官网示例

location / {
    auth_basic           "closed site";
    auth_basic_user_file conf/htpasswd;
}
  • auth_basic:启用使用“HTTP基本身份验证”协议验证用户名和密码。使用语法是auth_basic string | off,默认是off
  • auth_basic_user_file file,指定保存用户名和密码的文件,没有默认值,文件内格式如下:
    name1:password1
    name2:password2:comment
    name3:password3

3.配置示例

location / {
          auth_basic "Welcome, please login!";
          auth_basic_user_file /etc/nginx/conf.d/passwd.txt;
          proxy_pass http://127.0.0.1:8000/;

安装htpasswd命令: yum install -y httpd-tools

创建passwd文件:

htpasswd -c /etc/nginx/db/passwd.db user1 

新建用户:

htpasswd -b /etc/nginx/db/passwd.db user2 passwd2

删除用户:

htpasswd -D /etc/nginx/db/passwd.db user2

热加载nginx配置:

nginx -t && nginx -s reload

效果如下:

image.png