在 Ubuntu/Debian 上配置 Apache 网页身份验证
如何在 Ubuntu/Debian Web 服务器上使用密码身份验证保护 Apache 网页?如何使用基本身份验证来限制对 Apache 上特定网页的访问?安装并配置 Apache Web 服务器后,您可能需要为网页配置密码身份验证。本指南将介绍如何使用基本身份验证设置受密码保护的目录。
Apache Web 服务器可以通过运行以下命令安装在 Ubuntu 或 Debian 服务器/工作站上。
sudo apt update
sudo apt -y install apache2
确认服务已启动。
$ systemctl status apache2
* apache2.service - The Apache HTTP Server
Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled)
Drop-In: /lib/systemd/system/apache2.service.d
`-apache2-systemd.conf
Active: active (running) since Mon 2023-06-05 23:45:36 UTC; 34s ago
Main PID: 3797 (apache2)
Tasks: 55 (limit: 1110)
CGroup: /system.slice/apache2.service
|-3797 /usr/sbin/apache2 -k start
|-3799 /usr/sbin/apache2 -k start
`-3800 /usr/sbin/apache2 -k start
Jun 05 23:45:3 ubuntu-01 systemd[1]: Starting The Apache HTTP Server...
Jun 05 23:45:3 ubuntu-01 apachectl[3771]: AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1
Jun 05 23:45:3 ubuntu-01 systemd[1]: Started The Apache HTTP Server.
以下测试页面应该在服务器的 IP 地址/主机名上可见。
使用基本身份验证配置 Apache 密码保护目录。
安装 Apache Web 服务器后,安装基本身份验证包。
sudo apt -y install apache2-utils pwauth libapache2-mod-authnz-external
然后在/etc/apache2/sites-available目录下创建Apache网站配置文件。
sudo tee /etc/apache2/sites-available/secure-page.conf<<EOF
<Directory /var/www/html/secured>
AuthType Basic
AuthName "Basic Authentication"
AuthUserFile /etc/apache2/.htpasswd
require valid-user
</Directory>
EOF
将用户添加到基本身份验证文件。
$ sudo htpasswd -c /etc/apache2/.htpasswd webuser1
New password:
Re-type new password:
Adding password for user webuser1
“-c”选项用于在初始设置期间创建文件。要通过添加其他用户来更新文件,请使用:
$ sudo htpasswd /etc/apache2/.htpasswd webuser2
New password:
Re-type new password:
Adding password for user webuser2
包含用户的文件将包含:
$ cat /etc/apache2/.htpasswd
webuser1:$apr1$nIxlKLgc$xGTv.J1x5wtbJqAfFPt6o1
webuser2:$apr1$F4OnyIyv$WImqRIR5BBopTMjqGXs/c1
现在启用安全网站。
$ sudo a2ensite secure-page
Enabling site secure-page.
To activate the new configuration, you need to run:
systemctl reload apache2
创建安全网站目录。
sudo mkdir -p /var/www/html/secured
将内容添加到目录中以进行测试。
sudo tee /var/www/html/secured/index.html<<EOF
<html>
<body>
<div style="width: 100%; font-size: 50px; font-weight: bold; text-align: center;">
My secure web page - Using Basic Auth
</div>
</body>
</html>
EOF
重新启动 Apache 服务。
sudo systemctl restart apache2
测试对页面的访问。
当要求输入用户名和密码时,使用之前配置的凭据进行身份验证。
我们已确认基本身份验证可用于访问安全网页。相同的过程适用于保护服务器上现有网页的安全。
推荐阅读的 Linux 书籍:
- 适合初学者和专家的最佳 Linux 书籍
- 最佳 Linux 内核编程书籍
- 最佳 Linux Bash 脚本书籍
您也可以检查一下。
Ubuntu 上使用 SSL/TLS 保护 LDAP 服务器
适用于 Linux、macOS 和 Windows 的最佳安全备份应用程序
如何使用 SSL 证书保护 GitLab 服务器
如何在 Zimbra 上设置安全密码策略