ubuntu配置nginx htpasswd访问密码

Ubuntu 16.4 Nginx设置访问密码

1.安装apache2-utils

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
root@rodddy:/# apt-get install apache2-utils
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages were automatically installed and are no longer required:
libopts25 python-meld3 python-pkg-resources
Use 'apt autoremove' to remove them.
The following additional packages will be installed:
libapr1 libaprutil1
The following NEW packages will be installed:
apache2-utils libapr1 libaprutil1
0 upgraded, 3 newly installed, 0 to remove and 199 not upgraded.
Need to get 82.1 kB/245 kB of archives.
After this operation, 810 kB of additional disk space will be used.
Do you want to continue? [Y/n] y

2.创建用户名和密码,并把用户名和密码保存到指定文件中

创建用户admin 保存的文件位置/usr/local/src/nginx/passwd

1
2
3
4
root@roddy:~# htpasswd -c /usr/local/src/nginx/passwd admin
New password:
Re-type new password:
Adding password for user admin

3.修改nginx配置文件

1
2
3
4
5
6
7
8
9
10
11
12
server {
listen 80;
server_name localhost;
.......

#新增两行
auth_basic "Please input password"; #这里是提示信息
auth_basic_user_file /usr/local/src/nginx/passwd;

location /{
.......
}

4.先检查下配置文件

1
2
3
4
root@roddy:~# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
root@roddy:~#

5.重新加载配置文件

1
root@roddy:~# systemctl  reload nginx.service

备注:

htpasswd命令选项参数说明

-c 创建一个加密文件
-n 不更新加密文件,只将htpasswd命令加密后的用户名密码显示在屏幕上
-m 默认htpassswd命令采用MD5算法对密码进行加密
-d htpassswd命令采用CRYPT算法对密码进行加密
-p htpassswd命令不对密码进行进行加密,即明文密码
-s htpassswd命令采用SHA算法对密码进行加密
-b htpassswd命令行中一并输入用户名和密码而不是根据提示输入密码
-D 删除指定的用户

创建用户

1
root@roddy:~# htpasswd -c /usr/local/src/nginx/passwd admin

添加用户(在原文件下)

1
root@roddy:~# htpasswd  -b /usr/local/src/nginx/passwd  roddy 123456

删除用户

1
root@roddy:~# htpasswd -D /usr/local/src/nginx/passwd admin

修改密码

1
root@roddy:~# htpasswd -b /usr/local/src/nginx/passwd admin 12345678