#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Patch 生产 nginx.conf:新增 /h5/v20260807a/ 版本化 location + 将 /h5/go 302 指向它。 仅做确定性字符串替换,保持其他配置不变。""" import sys CONF = '/opt/wecom-it-desk/nginx/nginx.conf' OLD_GO = '/h5/v20260806g/$is_args$args' NEW_GO = '/h5/v20260807a/$is_args$args' BLOCK = '''location /h5/v20260807a/ { alias /usr/share/nginx/html/h5/; index index.html; try_files $uri /h5/v20260807a/index.html; add_header Cache-Control "no-store" always; add_header Strict-Transport-Security "max-age=31536000" always; add_header X-Frame-Options "SAMEORIGIN" always; add_header X-XSS-Protection "1; mode=block" always; add_header Referrer-Policy "no-referrer-when-downgrade" always; add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always; add_header Cross-Origin-Opener-Policy "same-origin" always; add_header X-Content-Type-Options "nosniff" always; } ''' with open(CONF, 'r', encoding='utf-8') as f: s = f.read() # 1) repoint /h5/go (all occurrences) n_go = s.count(OLD_GO) if n_go == 0: print('WARN: old /h5/go target not found, skip replace') else: s = s.replace(OLD_GO, NEW_GO) print('replaced /h5/go target occurrences:', n_go) # 2) insert versioned block before each 'location /h5/ {' marker = 'location /h5/ {' if marker not in s: print('ERROR: marker not found') sys.exit(2) segs = s.split(marker) out = segs[0] for seg in segs[1:]: out += BLOCK + marker + seg with open(CONF, 'w', encoding='utf-8') as f: f.write(out) print('inserted versioned block before', len(segs) - 1, 'occurrence(s) of', repr(marker)) print('new conf length:', len(out))