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

如何通过Shell脚本在nginx.conf首个未注释server {后添加配置

仅给Nginx配置中首个未注释的server {}添加nginx-status配置的Shell脚本方案

要实现只在第一个未被注释的server {}块下插入指定的nginx-status配置,我们可以用awk或sed工具精准控制匹配范围和执行次数,避免修改所有server {}项。

方案1:使用awk脚本(推荐,逻辑清晰易维护)

# 先备份原配置文件,防止操作失误
cp nginx.conf nginx.conf.bak

# 执行awk处理逻辑
awk '
processed == 0 && /^[[:space:]]*server[[:space:]]*{/ {
    print $0
    print "    location /nginx-status {"
    print "        stub_status on;"
    print "        allow all;"
    print "    }"
    processed = 1
    next
}
1' nginx.conf > nginx.conf.tmp && mv nginx.conf.tmp nginx.conf

逻辑说明:

  • processed == 0:通过标记变量确保仅处理一次匹配项
  • /^[[:space:]]*server[[:space:]]*{/:匹配行首允许有空格(适配Nginx配置的缩进)、无注释符号#的server {}行
  • 找到目标行后,先打印原行,再插入格式化好的nginx-status配置,最后将标记设为1,后续不再处理其他server {}
  • 末尾的1表示打印所有未被特殊处理的行

方案2:使用sed脚本(单行命令风格)

# 先备份原配置文件
cp nginx.conf nginx.conf.bak

# 执行sed处理逻辑
sed -e '0,/^[[:space:]]*server[[:space:]]*{/s//&\
    location \/nginx-status {\
        stub_status on;\
        allow all;\
    }/' nginx.conf > nginx.conf.tmp && mv nginx.conf.tmp nginx.conf

逻辑说明:

  • 0,/pattern/:限定匹配范围为从文件开头到第一个符合规则的server {}行
  • s//&\n.../:将匹配到的行保留(&代表匹配内容),并在其后换行插入指定配置
  • 注意转义路径中的/,以及用\实现换行,保证配置格式符合Nginx语法要求

后续验证

执行完脚本后,务必验证Nginx配置的合法性:

nginx -t

如果提示test is successful,再重启Nginx使配置生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 12:55:19