Skip to content

nginx 代理实现80端口访问多个服务

安装

bash
wget https://nginx.org/download/nginx-1.27.2.tar.gz
tar -zxvf nginx-1.27.2.tar.gz
cd nginx-1.27.2 
./configure 
make && make install

启动

bash
nginx -t
nginx
curl http://127.0.0.1

配置实现代理服务

bash
vim /usr/local/nginx/conf/nginx.conf

简单演示

添加代理 地址这样就可以通过80端口访问81端口了

text
location / {
    proxy_pass http://127.0.0.1:81;
    #root   html;
    #index  index.html index.htm;
}

http://127.0.0.1 实际请求就是http://127.0.0.1:81

http://127.0.0.1/hello -> http://127.0.0.1:81/hello

这里就出现了问题 任何请求都会代理到81端口 比方说这里有一个服务他是以/nacos 开始的是不是可以代理/nacos 开头的请求呢

代理指定前缀的请求

text
location /nacos {
    proxy_pass http://127.0.0.1:8848;
}

http://127.0.0.1/nacos -> http://127.0.0.1:8848/nacos

http://127.0.0.1/nacos/hello -> http://127.0.0.1:8848/nacos/hello

这时如果我的服务没有固定的前缀这时候该如何代理呢

代理请求路径替换

注意/ 不能丢

text
location /api/ {
    proxy_pass http://127.0.0.1:8080/;
}

这时代理就会发生一些变化 他会匹配 /api/ 开头的请求 但是实际请求中却不带/api

http://127.0.0.1/api/hello -> http://127.0.0.1:8080/hello

如果我要代理请求url中间的地址有/api/呢?

模糊匹配

text
location ~ /api/ {
    proxy_pass http://127.0.0.1:8080;
}

http://127.0.0.1/api/hello -> http://127.0.0.1:8080/api/hello

http://127.0.0.1/hello/api/hello -> http://127.0.0.1:8080/hello/api/hello