Skip to content

about

其实就是定义多个server代码块:

bash
http{
	# server区域块,可以存在多个,且默认是自上往下加载匹配
    server{
		listen 85;
		server_name localhost;
		charset utf-8;
		location / {
			root /data/py85/;
			index index.html;
		}
    }
    server{
		listen 5000;
		server_name localhost;
		charset utf-8;
		location / {
			root /data/;
			index index.html;
		}
    }
}

同域名-多端口虚拟机主机

配置

可以在任意目录下创建conf.d目录,我这里为了方便记忆,把它创建在了安装目录的conf目录内:

bash
mkdir -p /opt/nginx/conf/conf.d
chmod -R 777 /opt/nginx/conf/conf.d

在nginx的默认配置文件中:

bash
vim /opt/nginx/conf/nginx.conf

# 在http代码块中添加
http {
	include /opt/nginx/conf/conf.d/*.conf;
}

测试

先整俩测试用的html文件:

bash
mkdir -p /tmp/web
cat >/tmp/web/web1.html<<EOF
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>web1</h1>
</body>
</html>
EOF
cat /tmp/web1.html

cat >/tmp/web/web2.html<<EOF
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>web2</h1>
</body>
</html>
EOF
cat /tmp/web/web2.html

conf.d目录内,创建对应的nginx代理:

bash
cat >/opt/nginx/conf.d/web1.conf<<EOF
server {
    listen       5001;
    server_name  _5001;
    location / {
        root  /tmp/web;
        index web1.html;
        # 单入口的url路径转发
        try_files \$uri \$uri/ /web1.html;
    }
}
EOF
cat /opt/nginx/conf.d/web1.conf

cat >/opt/nginx/conf.d/web2.conf<<EOF
server {
    listen       5002;
    server_name  _5002;
    location / {
        root  /tmp/web;
        index web2.html;
        try_files \$uri \$uri/ /web2.html;
    }
}
EOF
cat /opt/nginx/conf.d/web2.conf

然后,你就可以浏览器通过IP和端口访问了:

bash
http://192.168.11.129:5001
http://192.168.11.129:5002

1832669904520609792.png

1832669904692576256.png 0.png)