目录
前言
利用虚拟主机,不用为每个要运行的网站提供一台单独的Nginx服务器或单独运行一组Nginx进程,虚拟主机提供了在同一台服务器、同一组Nginx进程上运行多个网站的功能。跟Apache一样,Nginx也可以配置多种类型的虚拟主机,分别是基于IP的虚拟主机、基于域名的虚拟主机、基于端口的虚拟主机。
一、基于域名的虚拟主机
1.添加域名解析
[root@localhost ~]# vim /etc/hosts
...
192.168.196.151 www.abc.com www.accp.com
2.准备虚拟站点网页文档
[root@localhost ~]# mkdir -p /var/www/html/abc
[root@localhost ~]# mkdir -p /var/www/html/accp
[root@localhost ~]# echo "<h1>www.abc.com</h1>" > /var/www/html/abc/index.html
[root@localhost ~]# echo "<h1>www.accp.com</h1>" > /var/www/html/accp/index.html
3.修改Nginx的配置文件
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
...
server {
listen 80;
server_name www.abc.com;
charset utf-8;
access_log logs/abc.access.log;
location / {
root /var/www/html/abc;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
server {
listen 80;
server_name www.accp.com;
charset utf-8;
access_log logs/accp.access.log;
location / {
root /var/www/html/accp;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
...
[root@localhost ~]# systemctl restart nginx.service
二、基于IP的虚拟主机
1.添加IP地址
[root@localhost ~]# vim /etc/hosts
...
192.168.196.151 www.abc.com
192.168.196.200 www.accp.com
2.设置虚拟网卡
[root@localhost ~]# ifconfig ens33:0 192.168.196.200/24
3.修改Nginx的配置文件
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
...
server {
listen 192.168.196.151:80;
server_name www.abc.com;
charset utf-8;
access_log logs/abc.access.log;
location / {
root /var/www/html/abc;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
server {
listen 192.196.151.200:80;
server_name www.accp.com;
charset utf-8;
access_log logs/accp.access.log;
location / {
root /var/www/html/accp;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
...
[root@localhost ~]# systemctl restart nginx.service
三、基于端口的虚拟主机
1.创建8080端口的网页文件
[root@localhost ~]# mkdir -p /var/www/html/accp8080
[root@localhost ~]# echo "<h1>www.accp8080.com</h1>" > /var/www/html/accp8080/index.html
2.修改Nginx的配置文件
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
...
server {
listen 192.168.196.200:8080;
server_name www.accp.com;
charset utf-8;
access_log logs/accp.access.log;
location / {
root /var/www/html/accp;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
[root@localhost ~]# systemctl restart nginx.service
总结
Nginx虚拟机主机搭建基于域名、基于IP和基于端口。