nginx 中的proxy_pass使用 demo

本文介绍了Nginx中proxy_pass指令的使用技巧,特别是如何通过在代理URL后添加斜杠来控制转发URL是否包含location匹配路径。举例展示了不同配置下实际代理地址的变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

概念前提
在proxy_pass中的代理url后加上/,代理转发的url中就不会带上location中匹配路径;
在proxy_pass中的代理url后面没有/,代理转发的url中就会带上location中的匹配路径
例如

server {
    listen       8080;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
        add_header Access-Control-Allow-Origin *;
    }

    location /nest/ {
      proxy_pass http://portal.com/nest/api/;
      client_max_body_size 1024m;
    }

    location /api/ {
      proxy_pass http://portal.com/mall/api/;
      client_max_body_size 1024m;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}


请求地址:
https://tmall.com/nest/open/topics
代理后真正的地址
http://portal.com/nest/api/open/topics
说明:/nest被替换成/nest/api

请求地址:
https://tmall.com/api/item/mall/search
代理地址:
http://portal.com/mall/api/item/mall/search
说明:/api被替换成/mall/api

相当于

server {
    listen       8080;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
        add_header Access-Control-Allow-Origin *;
    }

    location /nest {
      proxy_pass http://portal.com;
      client_max_body_size 1024m;
    }

    location /mall {
      proxy_pass http://portal.com;
      client_max_body_size 1024m;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

https://tmall-rn-test.geega.com/nest/api/open/topics =>
http://portal-refit.cloud-dev.geega.com/nest/api/open/topics

https://tmall-rn-test.geega.com/mall/api/item/mall/search =>
http://portal-refit.cloud-dev.geega.com/mall/api/item/mall/search

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值