Nginx中虚拟主机配置

发布时间 2023-12-18 15:57:33作者: 厚礼蝎

虚拟主机功能是Nginx经常用到的一个特性,每个虚拟主机就是一个独立的站点,对应一个域名,如果需要多个域名指向到一个IP上时,通过虚拟主机功能可以轻松实现。

下面在Nginx中创建三个虚拟主机,需要说明的是,这里仅仅列出了虚拟主机配置部分。

http{
     server {
         listen       80;
         server_name  www.abc1.com;
         charset utf-8;
         access_log  logs/host1.access.log  main;
         location / {
     	index index.html index.htm;
     	root /data/tp/abc1;
     	}
     }
     server {
         listen       80;
         server_name  www.abc2.com;
         charset utf-8;
         access_log  logs/host2.access.log  main;
         location / {
     	index index.html index.htm;
     	root /data/tp/abc2;
     	}
     }
     # 将主机配置单独放在文件中然后导入到主配置文件
     include /usr/local/nginx/conf/vhosts/www.abc3.conf;
}
$ cat /usr/local/nginx/conf/vhosts/www.abc3.conf;
server {
    listen       80;
    server_name  www.abc3.com;
    charset utf-8;
    access_log  logs/host3.access.log  main;
    location / {
	index index.html index.htm;
	root /data/tp/hxg3;
	}
}

然后在本地做解析

$ cat c:\windows\system32\drivers\etc\hosts
10.0.0.5    www.abc1.com
10.0.0.5    www.abc2.com
10.0.0.5    www.abc3.com

然后浏览器访问三个域名,得到不同的主页