1、htpasswd介绍安装
- Nginx的源码提供了ngx_http_auth_basic_module这个模块,它可以来解决web访问认证的问题。这个模块是默认就编译进nginx的,可以直接拿来使用。
- ngx_http_auth_basic_module它提供了最基本的http认证,这是http协议支持的,它会弹出一个框让你输入用户名和密码,只有用户名和密码输入正确了才能访问,这样就能保证自己的web不被任何人所访问。
- ngx_http_auth_basic_module是使用文件作为存储介质的,用户名是明文存储,而密码是加密之后再存储,这样在认证框输入的用户名和密码必须和文件的信息匹配才能认证成功。这里使用htpasswd这个命令来生成存放用户名和密码的文件。
- 安装命令如下:
# centos yum install -y httpd # ubuntu apt-get install -y apache2-utils
2、htpasswd --help
Usage:
htpasswd [-cimB25dpsDv] [-C cost] [-r rounds] passwordfile username
htpasswd -b[cmB25dpsDv] [-C cost] [-r rounds] passwordfile username password
htpasswd -n[imB25dps] [-C cost] [-r rounds] username
htpasswd -nb[mB25dps] [-C cost] [-r rounds] username password
-c Create a new file.
-n Don't update file; display results on stdout.
-b Use the password from the command line rather than prompting for it.
-i Read password from stdin without verification (for script usage).
-m Force MD5 encryption of the password (default).
-2 Force SHA-256 crypt() hash of the password (secure).
-5 Force SHA-512 crypt() hash of the password (secure).
-B Force bcrypt aencryption of the password (very secure).
-C Set the computing time used for the bcrypt algorithm
(higher is more secure but slower, default: 5, valid: 4 to 31).
-r Set the number of rounds used for the SHA-256, SHA-512 algorithms
(higher is more secure but slower, default: 5000).
-d Force CRYPT encryption of the password (8 chars max, insecure).
-s Force SHA-1 encryption of the password (insecure).
-p Do not encrypt the password (plaintext, insecure).
-D Delete the specified user.
-v Verify password for the specified user.
On other systems than Windows and NetWare the '-p' flag will probably not work.
The SHA-1 algorithm does not use a salt and is less secure than the MD5 algorithm.
3、简单使用
使用1:nginx配置文件中添加如下配置:
server {
listen 80;
listen [::]:80;
server_name localhost;
#access_log /var/log/nginx/host.access.log main;
location / {
auth_basic "Welcome to HZT-TEST's treasureHouse! Please input password:"; # 启用认证
auth_basic_user_file /etc/nginx/passwd; # 配置认证用户密码文件
root /usr/share/nginx/html;
index index.html index.htm;
}
...
}
其中,auth_basic string | off
是用来启用或关闭认证的,auth_basic_user_file filename
是用来配置认证用户密码文件的,filename是通过htpasswd命令生成的。
使用2:htpasswd添加用户并创建文件
$# htpasswd -c passwd test01
New password:
Re-type new password:
Adding password for user test01
使用3:不使用交互模式
$# htpasswd -bc passwd test01 123456
Adding password for user test01
使用4:在原有密码文件中生成一个用户
# 去掉参数-c,可在第一个用户后新增一个用户。添加-c会覆盖原本的用户信息。
$# htpasswd -b passwd test02 123456
Adding password for user test02
使用5:不更新密码文件,只将结果输出到屏幕
# htpasswd -bn test03 123456
test03:$apr1$mUJBhd1G$i75lBt3URbP11xoMU3YaP1
使用6:删除一个用户
$# htpasswd -D passwd test02
Deleting password for user test02
使用7:修改用户密码,跟新增用户一样
$# htpasswd -b passwd test01 123456
Updating password for user test01