本篇博客基于上一篇博客https://blog.csdn.net/weixin_42956047/article/details/90055449
环境:vm + centos 7
基于端口的虚拟主机
基于端口的虚拟主机环境并不多见,只需要修改主机监听的端口即可,域名可以相同。基于端口的虚拟主机是通过区分端口号来区分不同的主机,因为域名相同,只要端口不同就是不同的虚拟主机。
1 编辑配置文件
- 在系统配置目录下找到Nginx的配置文件,在文件中添加是三个server:
[root@localhost sbin]# cd /usr/local/nginx/conf
[root@localhost sbin]# vim nginx.conf
在文件中添加文档中没有内容:
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name www.abc.com;
location / {
root html/www;
index index.html index.htm;
}
}
server {
listen 81;
server_name www.abc.com;
location / {
root html/bbs;
index index.html index.htm;
}
}
server {
listen 82;
server_name www.abc.com;
location / {
root html/blog;
index index.html index.htm;
}
}
}
2 创建虚拟主机站点对应的目录和文件
[root@localhost conf]# cd /usr/local/nginx/html/
[root@localhost conf]# for n in 80 81 82
> do
> mkdir ${n}
> echo "http://www.abc.com:${n}" > ${n}/index.html
> done
3 编辑 /etc/hosts 文件,域名解析
echo "127.0.0.1 www.abc.com" >> /etc/hosts
4 重新加载 Nginx 配置
启动Nginx,如果Nginx已经启动,则平滑重启Nginx
[root@localhost conf]# /usr/local/nginx/sbin/nginx -t
[root@localhost conf]# /usr/local/nginx/sbin/nginx -s reload
5 访问测试
[root@localhost conf]# curl http://www.abc.com:80
http://www.abc.com:80
[root@localhost conf]# curl http://www.abc.com:81
http://www.abc.com:81
[root@localhost conf]# curl http://www.abc.com:82
http://www.abc.com:82
基于IP的虚拟主机
基于 IP 的虚拟主机在生产环境中不常使用,只需要将基于域名的虚拟主机中的域名修改为 IP 就可以了,前提是服务器有多个IP地址。如果需要不同的 IP 对应不同的服务,可在网站前端的负载均衡器上配置。
虚拟主机别名配置
虚拟主机别名,就是为虚拟主机设置除了主域名以外的一个或多个域名名字,这样就能实现用户访问的多个域名对应同一个虚拟主机网站的功能。
[root@localhost conf]# cat vhosts/www.abc.com.conf
server {
listen 80;
server_name www.abc.com abc.com; # 这里设置abc.com作为别名
location / {
root html/www;
index index.html index.htm;
}
}