49 lines
1.4 KiB
Python
49 lines
1.4 KiB
Python
#!/usr/bin/env python3
|
||
"""
|
||
把 /api/ 反代片段插入 drawlogo 站点的 **443 server 块**(幂等,可重复执行)
|
||
|
||
注意:不能用「第一个 location /」做锚点——那是 80 端口块。
|
||
这里改用 443 块独有的 access_log 行做锚点。
|
||
"""
|
||
import re
|
||
import sys
|
||
|
||
CONF = '/etc/nginx/sites-enabled/drawlogo-zhuig-com.conf'
|
||
SNIP = '/opt/drawlogo-api/deploy/nginx-location.conf'
|
||
ANCHOR = ' access_log /var/log/nginx/drawlogo_zhuig_access.log;'
|
||
|
||
text = open(CONF, encoding='utf-8').read()
|
||
|
||
# 1) 清理历史上放错位置的 /api/ 块(兼容 location /api/ 与 location ^~ /api/)
|
||
API_RE = re.compile(r'location\s+(?:\^~\s+)?/api/\s*\{')
|
||
|
||
while True:
|
||
m = API_RE.search(text)
|
||
if not m:
|
||
break
|
||
i = text.find('{', m.start())
|
||
depth = 0
|
||
end = -1
|
||
for j in range(i, len(text)):
|
||
if text[j] == '{':
|
||
depth += 1
|
||
elif text[j] == '}':
|
||
depth -= 1
|
||
if depth == 0:
|
||
end = j + 1
|
||
break
|
||
if end < 0:
|
||
print('ERROR: /api/ 块大括号不配对')
|
||
sys.exit(1)
|
||
text = text[:m.start()] + text[end:]
|
||
|
||
# 2) 插入到 443 块(锚点:该块独有的 access_log)
|
||
if ANCHOR not in text:
|
||
print('ERROR: 未找到 443 块的 access_log 锚点')
|
||
sys.exit(1)
|
||
|
||
snippet = open(SNIP, encoding='utf-8').read().rstrip() + '\n'
|
||
text = text.replace(ANCHOR, snippet + '\n' + ANCHOR, 1)
|
||
|
||
open(CONF, 'w', encoding='utf-8').write(text)
|
||
print('patched') |