1.7. 配置基于 Apache 名称的虚拟主机
基于名称的虚拟主机可让 Apache 为解析到服务器 IP 地址的不同域提供不同的内容。
您可以使用单独的文档根目录为 example.com 和 example.net 域设置虚拟主机。两个虚拟主机都提供静态 HTML 内容。
先决条件
客户端和 Web 服务器将
example.com和example.net域解析为 Web 服务器的 IP 地址。请注意,您必须手动将这些条目添加到 DNS 服务器中。
流程
安装
httpd软件包:# yum install httpd编辑
/etc/httpd/conf/httpd.conf文件:为
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 还将配置中找到的第一个虚拟主机用于与
ServerName和Server Alias参数中设置的任何域不匹配的请求。这还包括发送到服务器 IP 地址的请求。
-
为
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>为两个虚拟主机创建文档根目录:
# mkdir /var/www/example.com/ # mkdir /var/www/example.net/如果您在
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命令。如果您使用
firewalld,请在本地防火墙中打开端口80:# firewall-cmd --permanent --add-port=80/tcp # firewall-cmd --reload启用并启动
httpd服务:# systemctl enable --now httpd
验证
在每个虚拟主机的文档 root 中创建不同的示例文件:
# echo "vHost example.com" > /var/www/example.com/index.html # echo "vHost example.net" > /var/www/example.net/index.html-
使用浏览器并连接到
http://example.comWeb 服务器显示example.com虚拟主机中的示例文件。 -
使用浏览器并连接到
http://example.netWeb 服务器显示example.net虚拟主机中的示例文件。