Red Hat Training

A Red Hat training course is available for RHEL 8

1.7. 配置基于 Apache 名称的虚拟主机

基于名称的虚拟主机可让 Apache 为解析到服务器 IP 地址的不同域提供不同的内容。

您可以使用单独的文档根目录为 example.comexample.net 域建立虚拟主机。两个虚拟主机都提供静态 HTML 内容。

先决条件

  • 客户端和 Web 服务器将 example.comexample.net 域解析为 Web 服务器的 IP 地址。

    请注意,您必须手动将这些条目添加到 DNS 服务器中。

流程

  1. 安装 httpd 软件包:

    # yum install httpd
  2. 编辑 /etc/httpd/conf/httpd.conf 文件:

    1. example.com 域添加以下虚拟主机配置:

      <VirtualHost *:80>
          DocumentRoot "/var/www/example.com/"
          ServerName example.com
          CustomLog /var/log/httpd/example.com_access.log combined
          ErrorLog /var/log/httpd/example.com_error.log
      </VirtualHost>

      这些设置配置以下内容:

      • <VirtualHost *:80> 指令中的所有设置都是针对这个虚拟主机的。
      • DocumentRoot 设置虚拟主机的 Web 内容的路径。
      • ServerName 设置此虚拟主机为其提供内容服务的域。

        要设置多个域,请在配置中添加 ServerAlias 参数,并在此参数中指定用空格分开的额外域。

      • CustomLog 设置虚拟主机的访问日志的路径。
      • ErrorLog 设置虚拟主机错误日志的路径。

        注意

        Apache 还将配置中找到的第一个虚拟主机用于与ServerNameServer Alias参数中设置的任何域不匹配的请求。这还包括发送到服务器 IP 地址的请求。

  3. example.net 域添加类似的虚拟主机配置:

    <VirtualHost *:80>
        DocumentRoot "/var/www/example.net/"
        ServerName example.net
        CustomLog /var/log/httpd/example.net_access.log combined
        ErrorLog /var/log/httpd/example.net_error.log
    </VirtualHost>
  4. 为两个虚拟主机创建文档根目录:

    # mkdir /var/www/example.com/
    # mkdir /var/www/example.net/
  5. 如果您在 DocumentRoot 参数中设置的路径不在/var/www/中,请在两个文档根中设置 httpd_sys_content_t 上下文:

    # semanage fcontext -a -t httpd_sys_content_t "/srv/example.com(/.*)?"
    # restorecon -Rv /srv/example.com/
    # semanage fcontext -a -t httpd_sys_content_t "/srv/example.net(/.\*)?"
    # restorecon -Rv /srv/example.net/

    这些命令在/srv/example.com//srv/ example.net/ 目录中设置 httpd_sys_content_t上下文。

    请注意,您必须安装 policycoreutils-python-utils 软件包才能运行restorecon 命令。

  6. 如果使用 firewalld,请在本地防火墙中打开端口 80

    # firewall-cmd --permanent --add-port=80/tcp
    # firewall-cmd --reload
  7. 启用并启动 httpd 服务:

    # systemctl enable --now httpd

验证步骤

  1. 在每个虚拟主机的文档 root 中创建不同的示例文件:

    # echo "vHost example.com" > /var/www/example.com/index.html
    # echo "vHost example.net" > /var/www/example.net/index.html
  2. 使用浏览器并连接到 http://example.comWeb 服务器显示example.com虚拟主机中的示例文件。
  3. 使用浏览器并连接到 http://example.netWeb 服务器显示example.net虚拟主机中的示例文件。