Apache 虚拟主机配置教程:详细步骤和示例
本教程将引导您完成使用 Apache 配置虚拟主机的完整过程,包括安装、配置、创建首页文件以及测试访问。我们将使用 DNS 记录和不同的端口号创建两个虚拟主机,并提供详细的步骤和示例代码。
步骤
-
恢复至 DNS 服务完成后的快照
根据实际情况,使用虚拟化软件进行恢复。
-
安装 Apache
使用命令安装 Apache:
sudo yum install httpd安装完成后,启动 Apache 服务:
sudo systemctl start httpd -
测试默认网页
在物理机浏览器里输入服务器的 IP 地址,例如:
http://192.168.0.100/如果能够正常显示 Apache 的测试页,则说明 httpd 服务已经启动成功。
-
备份主配置文件
在进行修改之前,先备份主配置文件:
sudo cp /etc/httpd/conf/httpd.conf /etc/httpd/conf/httpd.conf.bak -
配置虚拟主机
打开主配置文件:
sudo vi /etc/httpd/conf/httpd.conf找到如下代码块:
# UseCanonicalName: Determines how Apache constructs self-referencing # URLs and the SERVER_NAME and SERVER_PORT variables. # When set 'Off', Apache will use the Hostname and Port supplied # by the client. When set 'On', Apache will use the value of the # ServerName directive. # UseCanonicalName Off在这个代码块下方添加如下内容:
# Virtual hosts IncludeOptional conf.d/*.conf保存并退出。
在 /etc/httpd/conf.d 目录下创建两个配置文件,分别为 www.conf 和 mail.conf:
sudo touch /etc/httpd/conf.d/www.conf sudo touch /etc/httpd/conf.d/mail.conf打开 www.conf 文件,添加如下内容:
<VirtualHost *:80> ServerName www.xxx.cn DocumentRoot /var/www/html/www </VirtualHost>打开 mail.conf 文件,添加如下内容:
<VirtualHost *:8000> ServerName mail.xxx.cn DocumentRoot /var/www/html/mail </VirtualHost>其中,/var/www/html/www 和 /var/www/html/mail 分别为两个虚拟主机的主页文件存放路径。可以根据实际情况进行修改。
-
创建虚拟主机的首页文件
在 /var/www/html/www 目录下创建一个 index.html 文件,添加如下内容:
<!DOCTYPE html> <html> <head> <title>www.xxx.cn</title> </head> <body> <h1>Welcome to www.xxx.cn!</h1> </body> </html>在 /var/www/html/mail 目录下创建一个 index.html 文件,添加如下内容:
<!DOCTYPE html> <html> <head> <title>mail.xxx.cn</title> </head> <body> <h1>Welcome to mail.xxx.cn!</h1> </body> </html> -
测试虚拟主机的访问
在物理机 Windows 系统的浏览器里,分别输入以下网址:
http://www.xxx.cn/ http://mail.xxx.cn:8000/如果能够正常显示两个虚拟主机的首页内容,则说明配置成功。
注意:在 Windows 系统中,需要将 DNS 记录添加到 hosts 文件中,以便正确解析域名。
验收标准
- 安装 Apache 之后,在物理机 Windows 系统的浏览器里,以 IP 地址打开 Apache 的测试页,截图保存。
- 配置虚拟主机后,在物理机 Windows 系统的浏览器里,分别以 www.xxx.cn 和 mail.xxx.cn:8000 打开两个虚拟主机的首页,截图保存。
原文地址: https://www.cveoy.top/t/topic/nRJI 著作权归作者所有。请勿转载和采集!