Apache实现一台服务器上运行多个网站
总共有三种方法:通过不同的IP地址
通过不同的域名
通过不同的端口号
(1).通过不同的IP地址实现
例如一台CentOS7有两个IP:192.168.5.101和192.168.5.103
[root@youxi1 conf]# cd /etc/httpd/conf.d/ [root@youxi1 conf.d]# vim test.conf //新建一个配置文件 <VirtualHost 192.168.5.101:9988> //IP和端口 ServerAdmin webmaster@dummy-host.example.com DocumentRoot /var/www/html/ //指向的路径 ServerName dummy-host.example.com ErrorLog logs/dummy-host.example.com-error_log CustomLog logs/dummy-host.example.com-access_log common </VirtualHost> <VirtualHost 192.168.5.103:9988> //IP和端口 ServerAdmin webmaster@dummy-host.example.com DocumentRoot /var/www/html/test/ //指向的路径 ServerName dummy-host.example.com ErrorLog logs/dummy-host.example.com-error_log CustomLog logs/dummy-host.example.com-access_log common </VirtualHost> [root@youxi1 conf.d]# vim /var/www/html/index.php /var/www/html/index.html [root@youxi1 conf.d]# vim /var/www/html/test/index.html /var/www/html/test/index.html [root@youxi1 conf.d]# systemctl restart httpd.service
实验结果:
(2).通过不同的域名实现
首先需要在域名管理系统中将两个域名解析的IP地址指向同一个。
[root@youxi1 conf.d]# vim test.conf //新建一个配置文件 <VirtualHost *:9988> ServerAdmin webmaster@dummy-host.example.com DocumentRoot /var/www/html/ //指向的路径 ServerName www.youxi1.com ErrorLog logs/www.youxi1.com-error_log CustomLog logs/www.youxi1.com-access_log common </VirtualHost> <VirtualHost *:9988> ServerAdmin webmaster@dummy-host.example.com DocumentRoot /var/www/html/test/ //指向的路径 ServerName test.youxi1.com ErrorLog logs/test.youxi1.com-error_log CustomLog logs/test.youxi1.com-access_log common </VirtualHost> [root@youxi1 conf.d]# systemctl restart httpd.service
由于我没有DNS服务器,所以修改hosts文件
[root@youxi1 conf.d]# vim /etc/hosts 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 192.168.5.101 www.youxi1.com 192.168.5.101 test.youxi1.com
Windows修改在C:\Windows\System32\drivers\etc目录下的hosts文件
192.168.5.101 www.youxi1.com 192.168.5.101 test.youxi1.com
实验结果:
(3).通过不同的端口号实现
修改/etc/httpd/conf/https.conf文件,添加监听端口
Listen 9988 Listen 9989
接着再修改新建的test.conf
[root@youxi1 conf.d]# vim test.conf <VirtualHost *:9988> ServerAdmin webmaster@dummy-host.example.com DocumentRoot /var/www/html/ ServerName www.youxi1.com ErrorLog logs/www.youxi1.com-error_log CustomLog logs/www.youxi1.com-access_log common </VirtualHost> <VirtualHost *:9989> ServerAdmin webmaster@dummy-host.example.com DocumentRoot /var/www/html/test/ ServerName www.youxi1.com ErrorLog logs/www.youxi1.com-error_log CustomLog logs/www.youxi1.com-access_log common </VirtualHost> [root@youxi1 conf.d]# systemctl restart httpd.service [root@youxi1 conf.d]# vim /etc/hosts 192.168.5.101 www.youxi1.com
Windows修改在C:\Windows\System32\drivers\etc目录下的hosts文件
192.168.5.101 www.youxi1.com
实验结果: