1.1安装httpd
# yum install httpd -y
1.2禁用默认的主机模式
# vim /etc/httpd/conf/httpd.conf
添加以下内容
#DocumentRoot "/var/www/html"
2.基于IP的虚拟主机配置
2.1为主机添加多个IP
# ip addr show dev eth0 #查看原有IP
# ip addr add 192.168.137.201/24 dev eth0 #添加一个IP
# ip addr show dev eth0 #查看添加后的IP信息, 此时有2个IP地址了。
2.2添加虚拟主机配置文件
# cd /etc/httpd/conf.d/ #进入配置目录
# vim virtualhost.conf #创建一个配置文件, 编辑内容如下
# cat virtualhost.conf #查看并检查配置文件
# cd /var/www #切换目录
# mkdir test200 test201 #创建目录
# echo test200 >>./test200/index.html #创建IP为200的主页
# echo test201 >>./test201/index.html #创建IP为200的主页
3基于端口的虚拟主机配置
3.1在主配置文件添加监听端口
vim /etc/httpd/conf/httpd.conf
Listen 8080
3.2添加8080的端口虚拟配置
#cat virtualhost.conf
<VirtualHost 192.168.137.200:80>
DocumentRoot "/var/www/test200"
ServerName www.test200.com
</VirtualHost>
<VirtualHost 192.168.137.201:80>
DocumentRoot "/var/www/test201"
ServerName www.test201.com
</VirtualHost>
#下面的内容是在上面的配置的基础上添加的。
<VirtualHost 192.168.137.201:8080>
DocumentRoot "/var/www/test201-8080"
ServerName www.test201-8080.com
</VirtualHost>
# cd /var/www/ #切换目录
# mkdir test201-8080 #创建目录
# echo "test201-8080" >>./test201-8080/index.html #创建主页
3.3测试
# service httpd restart
Stopping httpd: [ OK ]
Starting httpd: httpd: Could not reliably determine the server's fully qualified domain name, using localhost.localdomain for ServerName
[ OK ]
# elinks -source 192.168.137.201:80
test201
# elinks -source 192.168.137.201
test201
# elinks -source 192.168.137.201:8080
test201-8080
4基于域名的虚拟主机配置
4.1 添加域名的虚拟主机配置
# vim virtualhost.conf #编辑虚拟主机配置文件
# cat virtualhost.conf #内容如下, 红色部分是在上面的基础上添加的
NameVirtualHost 192.168.137.200:80
<VirtualHost 192.168.137.200:80>
DocumentRoot "/var/www/test200"
ServerName www.test200.com
</VirtualHost>
<VirtualHost 192.168.137.200:80>
DocumentRoot "/var/www/test200net"
ServerName www.test200.net
</VirtualHost>
<VirtualHost 192.168.137.201:80>
DocumentRoot "/var/www/test201"
ServerName www.test201.com
</VirtualHost>
<VirtualHost 192.168.137.201:8080>
DocumentRoot "/var/www/test2018080"
ServerName www.test2018080.com
</VirtualHost>
# !ser
service httpd restart
Stopping httpd: [ OK ]
Starting httpd: httpd: Could not reliably determine the server's fully qualified domain name, using localhost.localdomain for ServerName
[ OK ]
# cd /var/www #切换目录
# mkdir test200net #创建目录
# echo "test200net" >>./test200net/index.html #创建主页
4.2测试
添加域名解析
# vim /etc/hosts 编辑hosts文件, 添加两行
# cat /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.137.200 www.test200.com
192.168.137.200 www.test200.net
# elinks -source http://www.test200.com #测试.com域
test200
# elinks -source http://www.test200.net #测试.net域
test200net