虚拟主机:将一台物理服务器划分成多个虚拟的服务器,分别对外提供不同服务,这样的好处就是极大的节省了服务器硬件的成本,因此深受草根站长们的喜爱。

关于虚拟主机---百度百科

 

目的:本文主要介绍 nginx服务虚拟主机的配置方法


查看默认配置文件中关于虚拟主机配置的参考方法

[root@VM_16_8_centos nginx]# vim /etc/nginx/nginx.conf.default
 84     #server {
 85     #    listen       8000;
 86     #    listen       somename:8080;
 87     #    server_name  somename  alias  another.alias;
 88
 89     #    location / {
 90     #        root   html;
 91     #        index  index.html index.htm;
 92     #    }
 93     #}

Nginx配置虚拟主机,只要在http块中添加一个server块就可以(每一个server块都是一个虚拟主机)

注意到,在nginx主配置文件"/etc/nginx/nginx.conf"的http块中,有

 include /etc/nginx/conf.d/*.conf;

 我们可以在"/etc/nginx/conf.d/"这个目录中定义一个子配置文件,专门用来本实验的配置

 

 


基于端口号配置


1.编写子配置文件  

[root@VM_16_8_centos nginx]# pwd
/etc/nginx
[root@VM_16_8_centos nginx]# cd conf.d
[root@VM_16_8_centos conf.d]# touch virtual.conf
[root@VM_16_8_centos conf.d]# vim virtual.conf

server {
        listen 8001;
        server_name 111.230.102.233;
        root html/html8001;
        index index.html index.htm;
}

server {
        listen 8002;
        server_name 111.230.102.233;
        root html/html8002;
        index index.html index.htm;
}

 


2.在nginx 的root目录下创建html8001、html8002目录,并放置一个简单的index.html文件

[root@VM_16_8_centos nginx]# cd /usr/share/nginx/html
[root@VM_16_8_centos html]# mkdir html8002
[root@VM_16_8_centos html]# mkdir html8001
[root@VM_16_8_centos html]# echo "hello 8002" &> ./html8002/index.html
[root@VM_16_8_centos html]# echo "hello 8001" &> ./html8001/index.html


3.重启nginx服务

[root@VM_16_8_centos html8002]# systemctl restart nginx


4.查看效果

 


基于IP配置

确定服务器有两个以上的网卡设备,才可能有多个IP进行映射。可以用VMware模拟环境下实验。这里把配置贴出来做一个参考

server {
        listen 80;
        server_name 192.168.10.1;
        root html/192.168.10.1;
        index index.html index.htm;
}

server {
        listen 8002;
        server_name 192.168.10.2;
        root html/192.168.10.2;
        index index.html index.htm;
}

测试方法与上面一致

 

 

基于域名

1.配置文件

[root@VM_16_8_centos conf.d]# pwd
/etc/nginx/conf.d
[root@VM_16_8_centos conf.d]# ls
virtual.conf
[root@VM_16_8_centos conf.d]# vim virtual.conf

server {
        listen 80;
        server_name www.benmoom.club;
        root html/benmoom;
        index index.html index.htm;
}

2.创建测试文件

[root@VM_16_8_centos nginx]# cd /usr/share/nginx/html
[root@VM_16_8_centos html]# mkdir benmoom
[root@VM_16_8_centos html]# echo "<h1>benmoom</h1>" &> ./benmoom/index.html

 

3.重启nginx服务

[root@VM_16_8_centos html8002]# systemctl restart nginx

 

4.这里使用我的域名做测试