如何在 Ubuntu 18.04 上使用 Apache 设置密码验证 [快速入门]

介绍

本教程将引导您通过在 Ubuntu 18.04 上运行的 Apache Web 服务器上的密码保护资产,完成这些步骤将为您的服务器提供额外的安全性,以便未经授权的用户无法访问您的页面的某些部分。

有关本教程的更详细版本,以及每个步骤的更多解释,请参阅 如何在Ubuntu 18.04上使用Apache设置密码身份验证

前提条件

要完成本教程,您需要在 Ubuntu 18.04 服务器上访问以下内容:

  • 您的服务器上的sudo用户
  • Apache2 Web 服务器
  • 使用 SSL 保护的网站

步骤 1 – 安装 Apache 实用程序包

我们将安装一个名为htpasswd的实用程序,这是apache2-utils包的一部分,用于管理访问受限制内容的用户名和密码。

1sudo apt update
2sudo apt install apache2-utils

步骤2:创建密码文件

我们将以以下方式创建第一个用户(用您选择的用户名替换 `first_username):

1sudo htpasswd -c /etc/apache2/.htpasswd first_username

您将被要求提供并确认用户的密码。

留下您想要添加的任何额外用户的 -c 参数,以免重写文件:

1sudo htpasswd /etc/apache2/.htpasswd another_user

步骤 3 – 配置 Apache 密码身份验证

在此步骤中,我们需要配置Apache来检查此文件,然后在服务我们的受保护的内容之前使用该网站的虚拟主机文件,但如果您没有访问或更喜欢使用.htaccess文件,则在更长的教程中有另一个选项。

使用文本编辑器,如 nano,打开您想要添加限制的虚拟主机文件:

1sudo nano /etc/apache2/sites-enabled/default-ssl.conf

在我们的示例中,我们将限制整个文档根,但您可以更改此列表以仅针对 Web 空间中的特定目录。

在此步骤中,在您的文件中添加以下突出的行:

 1[label /etc/apache2/sites-enabled/default-ssl.conf]
 2<VirtualHost *:80>
 3  ServerAdmin webmaster@localhost
 4  DocumentRoot /var/www/html
 5  ErrorLog ${APACHE_LOG_DIR}/error.log
 6  CustomLog ${APACHE_LOG_DIR}/access.log combined
 7
 8  <Directory "/var/www/html">
 9      AuthType Basic
10      AuthName "Restricted Content"
11      AuthUserFile /etc/apache2/.htpasswd
12      Require valid-user
13  </Directory>
14</VirtualHost>

用以下命令检查配置:

您可以重新启动服务器来执行您的密码策略,然后检查您的服务器的状态。

1sudo systemctl restart apache2
2sudo systemctl status apache2

步骤 4 – 确认密码身份验证

若要确认您的内容是受保护的,请尝试在网页浏览器中访问受限制的内容,您应提供用户名和密码提示:

Apache2 password prompt

相关教程

以下是有关本教程的更多详细指南的链接:

  • [如何在Ubuntu 18.04上使用Apache设置密码身份验证(https://andsky.com/tech/tutorials/how-to-set-up-password-authentication-with-apache-on-ubuntu-18-04)
  • [熟悉重要的Apache文件和目录 ]

](https://andsky.com/tech/tutorials/how-to-install-the-apache-web-server-on-ubuntu-18-04#step-6-%E2%80%93-getting-familiar-with-important-apache-files-and-directories)在我们的Apache安装指南。

  • [如何在Ubuntu 16.04上设置Apache虚拟主机(https://andsky.com/tech/tutorials/how-to-set-up-apache-virtual-hosts-on-ubuntu-16-04)
  • 如何使用.htaccess 文件.
Published At
Categories with 技术
comments powered by Disqus