Apache伺服器可以配置多個虛擬主機,從而為多個站點提供服務,其實質就是根據不同的策略,訪問不同的文件系統目錄。apache提供3種虛擬主機的策略,1.基於埠的虛擬主機;2.基於功能變數名稱的虛擬主機;3.基於IP的虛擬主機。 ...
實驗環境
- 一臺最小化安裝的CentOS 7.3虛擬機
配置基礎環境
1. 安裝apache
yum install -y httpd
2. 建立虛擬主機的根目錄
mkdir /var/wwwroot
mkdir /var/wwwroot/site1
mkdir /var/wwwroot/site2
echo -e "site1" >> /var/wwwroot/site1/index.html
echo -e "site2" >> /var/wwwroot/site2/index.html
3. 關閉CentOS的防火牆
setenforce 0
systemctl stop firewalld
systemctl disable firewalld
配置基於埠的虛擬主機
1. 編輯apache配置文件
vim /etc/httpd/conf.d/vhost.conf
2. 添加以下內容
Listen 8081
<VirtualHost *:8081>
DocumentRoot "/var/wwwroot/site1"
ErrorLog "logs/site1.error.log"
CustomLog "logs/site1.access.log" common
<Directory "/var/wwwroot/site1">
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Require all granted
</Directory>
</VirtualHost>
Listen 8082
<VirtualHost *:8082>
DocumentRoot "/var/wwwroot/site2"
ErrorLog "logs/site2.error.log"
CustomLog "logs/site2.access.log" common
<Directory "/var/wwwroot/site2">
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Require all granted
</Directory>
</VirtualHost>
3. 啟動apache服務
systemctl start httpd
4. 在宿主機訪問兩個站點
http://192.168.204.133:8081
http://192.168.204.133:8082
配置基於功能變數名稱的虛擬主機
1. 編輯apache配置文件
vim /etc/httpd/conf.d/vhost.conf
2. 修改為以下內容
<VirtualHost *:80>
DocumentRoot "/var/wwwroot/site1"
ServerName site1.test.com
ErrorLog "logs/site1.error.log"
CustomLog "logs/site1.access.log" common
<Directory "/var/wwwroot/site1">
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Require all granted
</Directory>
</VirtualHost>
<VirtualHost *:80>
DocumentRoot "/var/wwwroot/site2"
ServerName site2.test.com
ErrorLog "logs/site2.error.log"
CustomLog "logs/site2.access.log" common
<Directory "/var/wwwroot/site2">
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Require all granted
</Directory>
</VirtualHost>
3. 重啟apache服務
systemctl restart httpd
4. 在Windows上修改hosts
文件
編輯C:\Windows\System32\drivers\etc\hosts
文件,
添加以下內容(根據實際情況自己修改)
192.168.204.135 site1.test.com
192.168.204.135 site2.test.com
5. 在宿主機訪問兩個站點
http://site1.test.com/
http://site2.test.com/
配置基於IP的虛擬主機
1. 在虛擬機上增加兩個IP地址
ifconfig ens33:1 192.168.204.135
ifconfig ens33:2 192.168.204.136
2. 重新編輯apache配置文件
vim /etc/httpd/conf.d/vhost.conf
3. 修改配置文件為以下內容
<VirtualHost 192.168.204.135:80>
DocumentRoot "/var/wwwroot/site1"
ErrorLog "logs/site1.error.log"
CustomLog "logs/site1.access.log" common
<Directory "/var/wwwroot/site1">
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Require all granted
</Directory>
</VirtualHost>
<VirtualHost 192.168.204.136:80>
DocumentRoot "/var/wwwroot/site2"
ErrorLog "logs/site2.error.log"
CustomLog "logs/site2.access.log" common
<Directory "/var/wwwroot/site2">
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Require all granted
</Directory>
</VirtualHost>
4. 重啟apache服務
systemctl restart httpd
5. 在宿主機訪問兩個站點
http://192.168.204.135/
http://192.168.204.136/
本文鏈接:https://www.cnblogs.com/connect/p/apache-vhost.html