import psycopg2
 import configparser
 import urllib.parse
-import filecmp
 from util.LockFile import LockFile
 
 
+def replace_file_from_string(fn, s):
+    if os.path.isfile(fn):
+        with open(fn) as f:
+            old = f.read()
+        if old == s:
+            # No changes
+            return False
+
+    with open("{}.tmp".format(fn), "w") as f:
+        f.write(s)
+    os.rename("{}.tmp".format(fn), fn)
+
+
 class AuthorizedKeysDumper(object):
     def __init__(self, db, conf):
         self.db = db
          THEN 1 ELSE 0 END
 FROM repositories AS r WHERE approved ORDER BY name""")
         f = open("%s.tmp" % self.conf.get("paths", "gitweblist"), "w")
-        accessfile = open("%s.tmp" % self.conf.get("paths", "lighttpdconf"), "w")
-        accessfile.write("alias.url += (\n")
+
+        webrepos = []
 
         for name, anon, web, description, initialclone, tabwidth, owner, remoterepo in curs:
             allrepos[name] = 1
                     open(anonfile, "w").close()
                 # When anonymous access is allowed, create an entry so
                 # we can access it with http git.
-                accessfile.write(' "/git/%s.git/" => "%s/",' % (name, repopath))
-                accessfile.write("\n")
+                webrepos.append((name, repopath))
             else:
                 if os.path.isfile(anonfile):
                     os.remove(anonfile)
         os.chmod("%s.tmp" % self.conf.get("paths", "gitweblist"), 0o644)
         os.rename("%s.tmp" % self.conf.get("paths", "gitweblist"), self.conf.get("paths", "gitweblist"))
 
-        accessfile.write(")\n")
-        accessfile.close()
-        # Only rewrite the access file if it is actually different. And if
-        # it is, we need to also reload lighttpd at this point.
-        if os.path.isfile(self.conf.get("paths", "lighttpdconf")) and filecmp.cmp(
-            self.conf.get("paths", "lighttpdconf"),
-                "%s.tmp" % self.conf.get("paths", "lighttpdconf")):
-            # No changes, so just get rid of the temp file
-            os.remove("%s.tmp" % self.conf.get("paths", "lighttpdconf"))
-        else:
-            # File changed, so we need to overwrite the old one *and*
-            # reload lighttpd so the changes take effect.
-            os.rename("%s.tmp" % self.conf.get("paths", "lighttpdconf"),
-                      self.conf.get("paths", "lighttpdconf"))
+        if webrepos:
+            changed = False
+            if self.conf.has_option("paths", "lighttpdconf"):
+                if replace_file_from_string(
+                        self.conf.get("paths", "lighttpdconf"),
+                        "alias.url += (\n{}\n)\n".format("\n".join([' "/git/{}.git/" => "{}/",'.format(name, path) for name, path in webrepos])),
+                ):
+                    changed = True
+
+            if self.conf.has_option("paths", "nginxconf"):
+                if replace_file_from_string(
+                        self.conf.get("paths", "nginxconf"),
+                        """if ($args ~ "git-receive-pack") {{
+    return 403;
+}}
+
+if ($uri !~ "^/git/({})\.git") {{
+    return 404;
+}}
+""".format("|".join([name for name, path in webrepos])),
+                ):
+                    changed = True
+
+        if changed and self.conf.has_option("webserver", "reloadcommand"):
             os.system(self.conf.get("webserver", "reloadcommand"))
 
         # Now remove any repositories that have been deleted