一、原理
用 Apache Basic 基础认证,通过
htpasswd 生成账号密码文件,再在虚拟主机目录配置认证规则,访问网页就会弹出登录框。二、第一步:生成密码文件 & 账号
1. Windows XAMPP
- 打开 CMD,进入 Apache bin 目录:
cmd
cd D:\xampp\apache\bin
- 创建密码文件 + 第一个账号(-c 新建文件)
cmd
htpasswd -c "D:\xampp\apache\conf\.htpasswd" admin
回车后输入两次密码。
- 添加更多账号(不要加 -c!)
cmd
htpasswd "D:\xampp\apache\conf\.htpasswd" user1
htpasswd "D:\xampp\apache\conf\.htpasswd" user2
2. Linux CentOS / Ubuntu
先装工具:
bash
运行
# CentOS
yum install httpd-tools -y
# Ubuntu
apt install apache2-utils -y
建第一个账号:
bash
运行
htpasswd -c /etc/httpd/.htpasswd admin
加更多账号:
bash
运行
htpasswd /etc/httpd/.htpasswd user1
三、第二步:虚拟主机配置(核心)
在对应
<VirtualHost> 里面加 <Directory> 认证配置Windows 完整示例
apache
<VirtualHost *:80>
ServerName test.com
DocumentRoot "D:/xampp/htdocs/test"
<Directory "D:/xampp/htdocs/test">
AllowOverride All
AuthType Basic
AuthName "请输入账号密码访问"
# 密码文件路径
AuthUserFile "D:/xampp/apache/conf/.htpasswd"
# 允许所有合法账号登录
Require valid-user
</Directory>
</VirtualHost>
Linux 完整示例
apache
<VirtualHost *:80>
ServerName test.com
DocumentRoot /var/www/test
<Directory /var/www/test>
AllowOverride All
AuthType Basic
AuthName "请输入账号密码访问"
AuthUserFile /etc/httpd/.htpasswd
Require valid-user
</Directory>
</VirtualHost>
四、第三步:重启 Apache 生效
- Windows XAMPP:停止再启动 Apache
- Linux
bash
运行
# CentOS
systemctl restart httpd
# Ubuntu
systemctl restart apache2
五、只限制某个子目录(不整站加密)
只想给
/admin 目录加密码,网站首页不用:apache
<Directory "D:/xampp/htdocs/test/admin">
AllowOverride All
AuthType Basic
AuthName "后台需登录"
AuthUserFile "D:/xampp/apache/conf/.htpasswd"
Require valid-user
</Directory>
六、补充操作
- 修改已有用户密码
直接再执行一次创建命令即可,不用加
-c - 删除用户
打开
.htpasswd文件,删掉对应用户那一行 - 只允许指定单个账号
把
Require valid-user改成:
apache
Require user admin
七、常见报错
- 不弹登录框:路径写错、没重启 Apache
- 401 认证失败:账号密码输错、密码文件权限不足
- 403:目录缺少
Require all granted或路径不匹配