You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NGINX使用sub_filter修改proxy_pass location块内路径问题咨询

选型结论

  • 排除sub_filter:该指令仅用于修改返回给客户端的响应正文内容,不处理请求路径,完全不符合需求
  • 排除redirect:3xx跳转需要客户端重新发起请求,会改变客户端侧URL、增加额外请求,无必要
  • 最优方案:使用rewrite指令或者proxy_pass路径后缀替换,两种方式都在Nginx内部转发时处理,对客户端和Akamai完全无感知

具体实现方案

方案1:rewrite写法(适配性更高,推荐)

location /incoming_path {
      max_ranges 0;
      # 核心规则:将/incoming_path开头的路径替换为/new_path后转发,break表示不重新匹配location
      rewrite ^/incoming_path(.*)$ /new_path$1 break;
      proxy_pass https://$upstream_application:9002;
      proxy_ssl_server_name on;
      proxy_ssl_certificate     /etc/nginx/conf.d/server_cert.pem;
      proxy_ssl_certificate_key /etc/nginx/conf.d/server_key.pem;
      proxy_set_header Accept-Encoding "";
      proxy_set_header Host               $host;
      proxy_set_header X-Real-IP          $proxy_protocol_addr;
      # 若需要修改响应报文中的链接可保留以下配置,否则直接删除即可
      # sub_filter_types *;
      # sub_filter "https://$proxy_host/incoming_path" "https://$host/new_path";
      # sub_filter_once on;
}

方案2:proxy_pass后缀替换(写法更简洁)

# 注意location末尾加/,和proxy_pass的路径后缀对应
location /incoming_path/ {
      max_ranges 0;
      # proxy_pass末尾加/new_path/,Nginx会自动将/incoming_path/xxx替换为/new_path/xxx转发到上游
      proxy_pass https://$upstream_application:9002/new_path/;
      proxy_ssl_server_name on;
      proxy_ssl_certificate     /etc/nginx/conf.d/server_cert.pem;
      proxy_ssl_certificate_key /etc/nginx/conf.d/server_key.pem;
      proxy_set_header Accept-Encoding "";
      proxy_set_header Host               $host;
      proxy_set_header X-Real-IP          $proxy_protocol_addr;
}

注意事项

  • 修改配置后先执行nginx -t校验语法正确性,确认无报错后执行nginx -s reload生效
  • 你之前的配置中sub_filter行末尾漏写了分号,这也是该配置之前不生效的常见原因,如果需要替换响应内容记得补充分号

内容的提问来源于stack exchange,提问作者SnazzyBootMan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 18:54:07