在 Ubuntu 上为 Apache2 设置密码,通常是指为网站或特定目录设置访问密码(Basic Auth 认证),访客在浏览网页时会被要求输入用户名和密码。
以下是详细的操作步骤:
Apache 提供了一个名为 htpasswd 的工具来生成密码文件。首先需要确保安装了 apache2-utils:
sudo apt update
sudo apt install apache2-utils
创建一个存储用户名和密码的文件(建议放在 /etc/apache2/ 目录下,例如 .htpasswd),并添加第一个用户:
sudo htpasswd -c /etc/apache2/.htpasswd your_username
-c 表示创建新文件(仅第一次创建文件时使用)。your_username 替换为你想要设置的用户名。如果需要添加更多用户(不要加 -c,否则会覆盖原文件):
sudo htpasswd /etc/apache2/.htpasswd another_user
有两种常用的配置方式,推荐使用直接修改 Apache 配置的方式(更安全且性能更好)。
编辑你的站点配置文件(例如默认的 /etc/apache2/sites-available/000-default.conf,或者是你自己的站点配置):
sudo nano /etc/apache2/sites-available/000-default.conf
在 <VirtualHost *:80> 块内,或者针对特定目录添加 <Directory> 配置。例如保护 /var/www/html/admin 目录:
<Directory "/var/www/html/admin">
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /etc/apache2/.htpasswd
Require valid-user
</Directory>
AuthName 是浏览器弹窗时显示的提示信息。AuthUserFile 必须指向你刚才创建的密码文件绝对路径。保存并退出(Nano 中按 Ctrl+O 回车,再按 Ctrl+X)。
.htaccess 文件如果你不想修改 Apache 的主配置,可以在需要保护的目录下创建 .htaccess 文件:
sudo nano /var/www/html/admin/.htaccess
写入以下内容:
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /etc/apache2/.htpasswd
Require valid-user
并且确保 Apache 配置中允许该目录覆盖权限(在站点配置的 <Directory> 中设置 AllowOverride AuthConfig)。
在重启之前,先检查 Apache 配置是否有语法错误:
sudo apache2ctl configtest
如果输出 Syntax OK,就可以重启 Apache 使配置生效:
sudo systemctl restart apache2
打开浏览器,访问你设置了密码保护的目录(例如 http://你的服务器IP/admin)。浏览器应该会弹出用户名和密码输入框,输入刚才设置的凭据即可访问。
.htpasswd 包含敏感信息,建议确保只有 root 和 Apache 运行用户(www-data)能读取:sudo chown root:www-data /etc/apache2/.htpasswd
sudo chmod 640 /etc/apache2/.htpasswd