Nginx配置虚拟主机有如下三种方式:
方式一、基于主机多IP方式
- 配置多网卡多IP的方式
[root@web01 conf.d]# cat ip.conf
server {
listen 10.0.0.7:80;
server_name _;
location / {
root /code_ip_eth0;
index index.html;
}
}
server {
listen 172.16.1.7:80;
server_name _;
location / {
root /code_ip_eth1;
index index.html;
}
}
- 根据配置创建目录
mkdir /code_ip_eth0
echo "Eth0" > /code_ip_eth0/index.html
mkdir /code_ip_eth1
echo "Eth1" > /code_ip_eth1/index.html
- 重启nginx服务
systemctl restart nginx
- 使用curl命令测试
curl 172.16.1.7 Eth1
curl 172.16.1.7 Eth0
方式二、基于端口的配置方式
- 配置多端口的虚拟主机
[root@web01 conf.d]# vim port.conf
server {
listen 81;
location / {
root /code_81;
index index.html;
}
}
server {
listen 82;
location / {
root /code_82;
index index.html;
}
}
- 根据配置文件创建所需的目录
mkdir /code_8{1..2}
echo "81" > /code_81/index.html
echo "82" > /code_82/index.html
3.检查语法并重启服务
[root@web01 conf.d]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@web01 conf.d]# systemctl restart nginx
- 访问
http://10.0.0.7:82/
方式三、基于多个hosts名称方式(多域名方式)
- 准备多虚拟主机配置文件
[root@web01 conf.d]# cat test1.xxx.com.conf
server {
listen 80;
server_name test1.xxx.com;
location / {
root /code/test1;
index index.html;
}
}
[root@web01 conf.d]# cat test2.xxx.com.conf
server {
listen 80;
server_name test2.xxx.com;
location / {
root /code/test2;
index index.html;
}
}
- 根据配置文件创建对应的目录
[root@web01 conf.d]# mkdir /code/test{1..2} -p
[root@web01 conf.d]# echo "test1_server" > /code/test1/index.html
[root@web01 conf.d]# echo "test2_server" > /code/test2/index.html
[root@web01 conf.d]# nginx -t
[root@web01 conf.d]# systemctl restart nginx
- 配置域名解析
10.0.0.7 test1.xxx.com
10.0.0.7 test2.xxx.com
- 通过浏览器访问该网站
- nginx自查
1.修改完配置记得使用 nginx -t 检查语法
2.如果没有检查语法,直接重载导致报错。systemctl status nginx -l 查看错误信息
网友评论