#!/usr/bin/env python3 import datetime import re import shutil import subprocess import sys p = "/etc/nginx/conf.d/buryans-all.conf" t = open(p, encoding="utf-8").read() orig = t def block(name): m = re.search(r"server_name\s+%s\s*;" % re.escape(name), t) if not m: return None, None end = t.find("\n}", m.end()) return m, end # Home: add forwarded headers to oauth2 auth + oauth2 sign-in locations. m, end = block("home.buryans.ru") if m: b = t[m.end():end] if "X-Forwarded-Host" not in b: b = b.replace( "proxy_set_header Cookie $http_cookie;", "proxy_set_header Cookie $http_cookie;\n proxy_set_header X-Forwarded-Host $host;\n proxy_set_header X-Forwarded-Uri $request_uri;", ) b = b.replace( "location /oauth2/ {\n proxy_pass http://192.168.1.106:9130;", "location /oauth2/ {\n proxy_pass http://192.168.1.106:9130;\n proxy_set_header X-Forwarded-Host $host;\n proxy_set_header X-Forwarded-Uri $request_uri;", ) t = t[:m.end()] + b + t[end:] # Immich: tell Immich the external host/proto. m, end = block("immich.buryans.ru") if m: b = t[m.end():end] if "X-Forwarded-Host" not in b: b = b.replace( "location / {\n proxy_pass http://192.168.1.104:2283;", "location / {\n proxy_pass http://192.168.1.104:2283;\n proxy_set_header X-Forwarded-Host $host;\n proxy_set_header X-Forwarded-Port 443;", ) t = t[:m.end()] + b + t[end:] if t == orig: print("no changes") sys.exit(0) backup = f"{p}.before-sso-headers-{datetime.datetime.now():%Y%m%d_%H%M%S}" shutil.copy2(p, backup) open(p, "w", encoding="utf-8").write(t) r = subprocess.run(["nginx", "-t"], capture_output=True, text=True) print(r.stdout.strip().splitlines()[-1] if r.stdout.strip() else r.stderr.strip()[-300:]) if r.returncode != 0: shutil.copy2(backup, p) print("restored backup") sys.exit(1) subprocess.run(["systemctl", "reload", "nginx"], check=False) print("backup", backup) print("reloaded")