什么是虚拟主机:
答:虚拟主机指一台物理服务器划分为多个“虚拟”的服务器,这样就可以将一台物理服务器当做多个服务器来使用,从而可以配置多个网站。
nginx虚拟主机分为三种:
1. 基于域名的虚拟主机
2. 基于端口的虚拟主机
3. 基于ip的虚拟主机
一、配置基于域名的虚拟主机
1. 创建nginx发布路径/nginx
mkdir /nginx
2. 修改目录的属主属组
chown nginx:nginx /nginx
3. 创建一个html文件用于测试
echo "<h1>this is nginx yuming test </h1>" > /nginx/nginxyuming.html
4. 修改winds的hosts解析文件
#hosts位置
C:\Windows\System32\drivers\etc\hosts
#添加解析
192.168.245.66 www.nginxyuming.com
5. 修改nginx配置文件
vim /usr/local/nginx/conf/nginx.conf
#修http段种的server段内容
server {
listen 80;
server_name www.nginxyuming.com;
charset utf-8;
access_log /usr/local/nginx/logs/nginxyuming.log ;
location / {
root /nginx/ ;
index nginxyuming.html ;
}
二、配置基于ip的虚拟主机
1. 修改html文件,便于确认
echo "<h1>this is nginx ip test </h1>" > /nginx/nginxyuming.html
2. 编辑配置文件
vim /usr/local/nginx/conf/nginx.conf
server {
listen 192.168.245.66:80;
server_name 192.168.245.66;
charset utf-8;
access_log /usr/local/nginx/logs/nginxyuming.log ;
location / {
root /nginx/ ;
index nginxyuming.html ;
}
三、配置基于端口的虚拟主机
1. 修改html文件,便于确认
echo "<h1>this is nginx port 1234 test </h1>" > /nginx/nginxyuming.html
2. 编辑配置文件
vim /usr/local/nginx/conf/nginx.conf
server {
listen 192.168.245.66:1234;
server_name 192.168.245.66;
charset utf-8;
access_log /usr/local/nginx/logs/nginxyuming.log ;
location / {
root /nginx/ ;
index nginxyuming.html ;
}
注:可以写多个虚拟主机,在http段种添加server段和location段
四、多台虚拟主机配置
注:本文演示,基于ip的多台虚拟主机
1. 配置网卡临时接口
ifconfig ens33:0 192.168.245.88/24
2.创建/web目录并在/nginx和/web目录中添加html文件来区分两个主机
mkdir /web
chown nginx:nginx /web
echo "<h1>this is nginx ip 192.168.245.66 test </h1>" > /nginx/nginxyuming.html
echo "<h1>this is nginx ip 192.168.245.88 test </h1>" > /web/web.html
3. 编辑配置文件
vim /usr/local/nginx/conf/nginx.conf
server {
listen 192.168.245.66:80;
server_name 192.168.245.66;
charset utf-8;
access_log /usr/local/nginx/logs/nginxyuming-66.log ;
location / {
root /nginx/ ;
index nginxyuming.html ;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
server {
listen 192.168.245.88:80;
server_name 192.168.245.88;
charset utf-8;
access_log /usr/local/nginx/logs/nginxyuming-88.log ;
location / {
root /web/ ;
index web.html ;
}
#error_page 404 /404.html;
#
# # redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}