- 虚拟主机简介
利用虚拟主机,不用为每个要运行的网站提供一台单独的Nginx服务器或单独运行一组Nginx进程,虚拟主机提供了在同一台服务器,同一组 Nginx进程上运行多个网站的功能。跟Apache一样,Nginx也可以配置多种类型的虚拟主机,分别是基于IP的虚拟主机、基于域名的虚拟主机、基于端口的虚拟主机。
使用Nginx搭建虚拟主机服务器时,每个虚拟Web站点拥有独立的“serverf”配置段,各自监听的IP地址、端口号可以单独指定,当然网站名称也是不同的。
2.虚拟主机配置
测试网页准备
mkdir -p /usr/local/nginx/html/canyun/
mkdir -p /usr/local/nginx/html/wudi/
echo "www.canyun.com" > /usr/local/nginx/html/canyun/index.html
echo "www.wudi.com" > /usr/local/nginx/html/wudi/index.html
2.1基于域名的虚拟主机配置
2.1.1操作步骤
配置文件修改
修改配置文件/usr/local/nginx/conf/nginx.conf,把配置文件中的server{}代码段全部去掉,加入2个新的server{}段,对应2个域名。
vim /usr/local/nginx/conf/nginx.conf
####省略####
server {
listen 80;
server_name www.canyun.com;
charset utf-8;
access_log logs/www.canyun.com.access.log;
location / {
root /usr/local/nginx/html/canyun;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
server {
listen 80;
server_name www.wudi.com;
charset utf-8;
access_log logs/www.wudi.com.access.log;
location / {
root /usr/local/nginx/html/wudi;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
####省略####
重启服务
systemctl restart nginx.service
2.1.2 操作截图
2.配置文件修改
vim /usr/local/nginx/conf/nginx.conf
3.客户端配置域名解析
分别访问www.canyun.com与www.wudi.com(该域名有公网解析,别直接访问)
2.2 基于端口的虚拟主机配置
只需要一个IP地址的不同端口实现访问不同的网点
2.2.1 操作步骤
vim /usr/local/nginx/conf/nginx.conf
####省略####
server {
listen 192.168.80.20:80;
server_name www.canyun.com;
charset utf-8;
access_log logs/www.canyun.com.access.log;
location / {
root /usr/local/nginx/html/canyun;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
server {
listen 192.168.80.20:8080;
server_name www.wudi.com;
charset utf-8;
access_log logs/www.wudi.com.access.log;
location / {
root /usr/local/nginx/html/wudi;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
####省略####
重启服务
nginx -s reload
2.2.2 操作截图
2.3 基于IP的虚拟主机配置
2.3.1 操作步骤
#配置虚拟网卡
ifconfig ens33:1 192.168.80.50
vim /usr/local/nginx/conf/nginx.conf
####省略####
server {
listen 192.168.80.20:80;
server_name www.canyun.com;
charset utf-8;
access_log logs/www.canyun.com.access.log;
location / {
root /usr/local/nginx/html/canyun;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
server {
listen 192.168.80.50:80;
server_name www.wudi.com;
charset utf-8;
access_log logs/www.wudi.com.access.log;
location / {
root /usr/local/nginx/html/wudi;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
####省略####
重启服务
nginx -s reload
2.3.2 操作截图
客户端访问测试: