Apache 设置访问需要账号密码(完整教程,支持单账号 / 多账号)

一、原理

用 Apache Basic 基础认证,通过 htpasswd 生成账号密码文件,再在虚拟主机目录配置认证规则,访问网页就会弹出登录框。

二、第一步:生成密码文件 & 账号

1. Windows XAMPP

  1. 打开 CMD,进入 Apache bin 目录:
cmd
cd D:\xampp\apache\bin
  1. 创建密码文件 + 第一个账号(-c 新建文件)
cmd
htpasswd -c "D:\xampp\apache\conf\.htpasswd" admin
回车后输入两次密码。
  1. 添加更多账号(不要加 -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>

六、补充操作

  1. 修改已有用户密码

    直接再执行一次创建命令即可,不用加 -c

  2. 删除用户

    打开 .htpasswd 文件,删掉对应用户那一行

  3. 只允许指定单个账号

    Require valid-user 改成:

apache
Require user admin

七、常见报错

  • 不弹登录框:路径写错、没重启 Apache
  • 401 认证失败:账号密码输错、密码文件权限不足
  • 403:目录缺少 Require all granted 或路径不匹配
上一篇 华为CE交换机-配置跨AS的Segment VXLAN实现三层互通
下一篇 乌班图Ubuntu配置网络