nginx配置auth_basic登录认证的方法

安装htpasswd

1
2
3
4
5
# ubuntu
sudo apt-get install apache2-utils

# centos
sudo yum -y install httpd-tools

htpasswd 参数说明

1
2
3
4
5
6
7
8
-c 创建passwdfile.如果passwdfile 已经存在,那么它会重新写入并删去原有内容.
-n 不更新passwordfile,直接显示密码
-m 使用MD5加密(默认)
-d 使用CRYPT加密(默认)
-p 使用普通文本格式的密码
-s 使用SHA加密
-b 命令行中一并输入用户名和密码而不是根据提示输入密码,可以看见明文,不需要交互
-D 删除指定的用户

生成密码

1
2
3
4
5
6
# 进入密码存储目录
cd /etc/nginx/conf.d/passwd

# 生成密码
htpasswd -c ./passwdfile username
# 执行上命令后会要求输入两次密码,./passwdfile 是在当前目录下创建密码文件passwdfile ,username即为需要设置的账号

nginx 载入配置

在nginx的 server段内,找到要加入账号验证的location路径

1
2
3
4
5
location /docs {
alias /www/wwwroot/dy_admin/docs;
auth_basic "请输入账号密码";
auth_basic_user_file /etc/nginx/conf.d/passwd/passwdfile; #密码存储文件路径
}