目录
1.1)使用 ngx_http_auth_basic_module 模块进行配置
一、Nginx 配置项
1.1)使用 ngx_http_auth_basic_module 模块进行配置
命令为 auth_basic,语法格式如下:
语法:
auth_basic string | off; # string 会在弹窗中显示
默认值(默认状态为不开启认证):
auth_basic off;
可配置段:
http, server, location, limit_except
1.2)配置存储用户和密码的文件
语法:
auth_basic_user_file auth_file;
默认值:无
可配置段:
http, server, location, limit_except
二、配置 Nginx
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
root /home/web;
auth_basic "for nginx auth";
auth_basic_user_file conf/server.auth; # 存储用户和密码的文件
# auth_basic_user_file /home/web/authconf/server.auth; # 也可以使用绝对路径,但是这个路径,nginx 必须要有可读权限
autoindex on;
location / {
}
}
三、user_file 的内容
在 user file 中存储的是用户名和密码,形式如下:
a-username:hash-password
其中密码是需要经过加密的,加密方式可以是 htpasswd,也可以是 openssl。
使用 openssl 加密:
$ openssl passwd -crypt a-simple-password # 假设密码是 a-simple-password
Warning: truncating password to 8 characters
K5tJruB33QlDo # 加密后的密码就是 K5tJruB33QlDo,在 user file 中填写的就是用户名和这个加密后的密码
使用 htpasswd 加密:
$ htpasswd -bn b-username b-simple-password
b-username:$apr1$eTtMA2S/$pOeX.9XeDYG9xPBd3I6Ii0
所以 user_file 的内容如下(a-username 的密码是使用 openssl 命令生成的,b-username 的密码是使用 htpasswd 命令生成的):
a-username:K5tJruB33QlDo
b-username:$apr1$eTtMA2S/$pOeX.9XeDYG9xPBd3I6Ii0
四、测试
可以使用如下命令进行测试:
# 测试 a-username
$ curl -u a-username:a-simple-password http://127.0.0.1
# 测试 b-username
$ curl -u b-username:b-simple-password http://127.0.0.1
五、重启 Nginx 生效
/usr/sbin/nginx -s reload