1. 基於IP的虛擬主機配置
1.1 創建虛擬主機配置文件
[root@CentOS7 ~]# cd /usr/local/nginx/conf
[root@CentOS7 conf]# mkdir vhost
[root@CentOS7 conf]# vim vhost/vhost1.conf
server{
listen 80;
server_name 192.168.146.102;
location / {
root conf/vhost/test1;
index index.html index.htm;
}
}
1.2 將虛擬主機配置文件包含進主配置文件
[root@CentOS7 ~]# vim /usr/local/nginx/conf/nginx.conf
116 include vhost/*.conf;
2.3 先測試配置文件然後重新加載Nginx
[root@CentOS7 nginx]# /usr/local/nginxsbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@CentOS7 nginx]# kill -HUP `cat logs/nginx.pid`
2.4 創建虛擬主機目錄並創建測試文件index.html
[root@CentOS7 conf]# mkdir -p vhost/test1/
[root@CentOS7 conf]# echo "this is configuration file for virtual host" > vhost/test1/index.html
2.5 測試文件
2. 基於域名的虛擬主機配置
2.1 創建虛擬主機配置文件
[root@CentOS7 conf]# vim vhost/vhost2.conf
server{
listen 80;
server_name www.test2.com;
location / {
root conf/vhost/test2;
index index.html index.htm;
}
}
2.2 重啓nginx
由於上面已將虛擬主機配置文件包含進主文件,故以下均不在配置。
[root@CentOS7 nginx]# kill -HUP `cat /usr/local/nginx/logs/nginx.log`
2.3 配置hosts文件
基於域名訪問,需要將域名和IP地址的映射寫入/etc/hosts。
[root@CentOS7 vhost]# echo "192.168.146.102 www.test2.com" >> /etc/hosts
2.4 創建虛擬主機目錄並創建測試文件index.html
[root@CentOS7 conf]# mkdir -p /vhost/test2/
[root@CentOS7 conf]# echo "this is the configuration file for domain_name" > vhost/test2/index.html
2.5 測試
注:若要在windwos端基於域名訪問,需再C:\Windows\System32\drivers\etc\host文件夾內添加192.168.73.142 www.test2.com。
3. 基於端口的虛擬主機配置
3.1 創建虛擬主機配置文件
[root@CentOS7 conf]# vim vhost/vhost3.conf
server{
listen 8080;
server_name www.test3.com;
location / {
root conf/vhost/test3;
index index.html index.htm;
}
}
3.2 重啓nginx
[root@CentOS7 nginx]# kill -HUP `cat logs/nginx.pid`
3.3 配置hosts文件
[root@CentOS7 conf]# echo "192.168.146.102 www.test3.com" >> /etc/hosts
3.4 創建虛擬主機目錄並創建測試文件index.html
[root@CentOS7 conf]# mkdir vhost/test3
[root@CentOS7 conf]# echo "this is configruation file for only port" > conf/test3/index.html
3.5 測試