一.基于ip
1) ifconfig 查看自己的网卡接口为enp2s0,
vi /etc/sysconfig/network-scritps/ifc-enp2s0:0
DEVICE="enp2s0:0"
IPADDR=192.168.100.100
BOOTPROTO=none
ONBOOT=yes
NETMASK=255.255.255.0
systemctl restart network
这样就创建好了一个虚拟网卡接口
2)vi /etc/hosts
192.168.200.100 www.virtual1.com
192.168.200.101 www.virtual2.com
3)在/etc/httpd/conf/httpd.conf里面 加上
Include /etc/httpd/conf/virtualhost/virtual1.conf
mkdir /var/www/html/{virtual1,virtual2} #virtual1和virtual2的DocumentRoot目录
cd /etc/httpd/conf && mkdir virtualhost && cd virtualhost && touch {virtual1.conf ,virtual2.conf}
#virtual1和virtual2的配置文件
cd /etc/httpd/logs && mkdir virtualhost #这个目录用来存放virtual1的日志文件
4)vi /etc/httpd/conf/virtualhost/virtual1.conf
<VirtualHost 192.168.100.100:80>
ServerName www.virtual1.com
ServerAlias www.virtual1.com.cn #别名
DocumentRoot /var/www/html/virtual1
DirectoryIndex virtual1.html
ErrorLog /etc/httpd/logs/virtualhost/error_virtual1_log
CustomLog /etc/httpd/logs/virtualhost/access_virtual1_log combined
<Directory /var/www/html/virtual1>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
</VirtualHost>
<VirtualHost 192.168.100.101:80>
ServerName www.virtual2.com
ServerAlias www.virtual2.com.cn #别名
DocumentRoot /var/www/html/virtual2
DirectoryIndex virtual2.html
ErrorLog /etc/httpd/logs/virtualhost/error_virtual2_log
CustomLog /etc/httpd/logs/virtualhost/access_virtual2_log combined
<Directory /var/www/html/virtual2>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
</VirtualHost>
二.基于域名
主要是用一个ip对应多个域名,节约ip.
1)vi /etc/hosts
192.168.200.156 www.virtual1.com
192.168.200.156 www.virtual2.com
2)vi /etc/httpd/conf/virtualhost/virtual1.conf
<VirtualHost 192.168.200.156:80>
ServerName www.virtual1.com
DocumentRoot /var/www/html/virtual1
ErrorLog /etc/httpd/logs/virtualhost/error_virtual1_log
CustomLog /etc/httpd/logs/virtualhost/access_virtual1_log
<Directory /var/www/html/virtual1>
Require all granted
DirectoryIndex virtual1.html
</Directory>
</VirtualHost >
vi /etc/httpd/conf/virtualhost/virtual2.conf
<VirtualHost 192.168.200.156:80>
ServerName www.virtual2.com
DocumentRoot /var/www/html/virtual2
ErrorLog /etc/httpd/logs/virtualhost/error_virtual2_log
CustomLog /etc/httpd/logs/virtualhost/access_virtual2_log
<Directory /var/www/html/virtual2>
Require all granted
DirectoryIndex virtual2.html
</Directory>
</VirtualHost >
三.基于端口
1)vi /etc/httpd/conf/httpd.conf
加个监听端口 listen 8080
2)修改virtual1的virtual2的配置文件
<VirtualHost 192.168.200.156:80>
DocumentRoot /var/www/html/virtual1
ServerName www.virtual1.com
<Directory /var/www/html/virtual1>
DirectoryIndex virtual1.html
Require all granted
</Directory>
</VirtualHost>
<VirtualHost 192.168.200.156:8080>
DocumentRoot /var/www/html/virtual2
ServerName www.virtual2.com
<Directory /var/www/html/virtual2>
DirectoryIndex virtual2.html
Require all granted
</Directory>
</VirtualHost>
这样就ok了.
本文转自神ge 51CTO博客,原文链接:http://blog.51cto.com/12218412/1883043