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

如何定位Nginx配置中指定location块并替换内部端口?

替换Nginx指定location块内的端口

需要修改Nginx配置中非注释的location /test/v2.0.0块内的proxy_pass端口,将:3000替换为:5555,其他location块的配置保持不变。

原始配置

server {
    location /test/v2.0.3 {
        modsecurity on;
        proxy_pass http://10.1.0.6:3000;
    }
    location /test/v2.0.0 {
        modsecurity on;
        proxy_pass http://10.1.0.6:3000;
    }
}

尝试过的sed命令及问题

  • sed '0,/:[0-9].*;/{s/:[0-9].*;/:5555;/}' test.nginx:只会修改第一个匹配到的端口,无法精准定位到目标location块
  • sed '/.*location.*\/test\/v2.0.0\/.*:[0-9].*;/{s/:[0-9].*;/:5555;/}' test.nginx:无任何修改,原因是正则多了结尾的/(原始配置里location /test/v2.0.0后面没有这个斜杠),且试图在同一行匹配location和端口,实际两者不在同一行
  • sed 's/.*location.*\/test\/v2.0.0\/.*:[0-9].*;/:5555;/' test.nginx:无任何修改,同样是正则错误,还错误地试图替换整行内容

正确的sed命令

用sed的地址范围匹配可以精准定位目标块并替换:

sed '/^[^#]*location \/test\/v2\.0\.0 {/,/}/s/:3000;/:5555;/' test.nginx

命令逻辑

  1. 锁定目标块:/^[^#]*location \/test\/v2\.0\.0 {/,/}/ 匹配从非注释的location /test/v2.0.0 {行开始,到对应的闭合}结束的所有内容,确保只在目标location块内操作
    • ^[^#]*:保证这一行不是注释行(行首没有#)
    • \/test\/v2\.0\.0:转义特殊字符/和.,精准匹配路径
  2. 执行替换:在上述匹配范围内,把:3000;替换为:5555;

如果要直接修改原文件(原地替换),加上-i参数即可:

sed -i '/^[^#]*location \/test\/v2\.0\.0 {/,/}/s/:3000;/:5555;/' test.nginx

预期输出

server {
    location /test/v2.0.3 {
        modsecurity on;
        proxy_pass http://10.1.0.6:3000;
    }
    location /test/v2.0.0 {
        modsecurity on;
        proxy_pass http://10.1.0.6:5555;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 05:07:12