要在Nginx中使用htpasswd对网站进行密码保护,可以按照以下步骤操作:
htpasswd通常随Apache工具包一起提供。在大多数Linux发行版中,可以通过以下命令安装:
# Debian/Ubuntu
sudo apt-get install apache2-utils
# CentOS/RHEL
sudo yum install httpd-tools
sudo htpasswd -c /etc/nginx/.htpasswd username
系统会提示你输入并确认密码。
-c
参数表示创建新文件(如果文件已存在会覆盖)-c
参数:
bash
sudo htpasswd /etc/nginx/.htpasswd anotheruser
编辑Nginx配置文件(通常在/etc/nginx/sites-available/your_site
或/etc/nginx/nginx.conf
):
server {
listen 80;
server_name yourdomain.com;
location / {
auth_basic "Restricted Content";
auth_basic_user_file /etc/nginx/.htpasswd;
# 其他配置...
}
}
sudo nginx -t # 测试配置是否正确
sudo systemctl reload nginx # 重载配置
location /protected/ {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
location /public/ {
auth_basic off;
}
htpasswd支持多种密码加密方式:
- -B
使用bcrypt(最安全但CPU消耗较大)
- -d
使用crypt()
- -s
使用SHA1
- -p
使用明文密码(不推荐)
例如使用bcrypt:
sudo htpasswd -B -c /etc/nginx/.htpasswd username
bash
sudo chown root:www-data /etc/nginx/.htpasswd
sudo chmod 640 /etc/nginx/.htpasswd
这样配置后,访问你的网站时就会弹出登录对话框,只有输入正确用户名和密码的用户才能访问受保护的内容。