ctucx.git: nixfiles

ctucx' nixfiles

commit 28a8f4bf719819d34cf85234d51cc1e3ae786fef
parent e302fbe3add88c69aed5dcbaef7072d353051118
Author: Leah (ctucx) <git@ctu.cx>
Date: Wed, 17 May 2023 10:13:22 +0200

modules/linux: add nginx-sni-proxy module
2 files changed, 52 insertions(+), 0 deletions(-)
M
modules/default.nix
|
1
+
A
modules/linux/nginx-sni-proxy.nix
|
51
+++++++++++++++++++++++++++++++++++++++++++++++++++
diff --git a/modules/default.nix b/modules/default.nix
@@ -15,6 +15,7 @@
      ./linux/dns.nix
      ./linux/gotosocial.nix
      ./linux/matrix-sliding-sync.nix
+     ./linux/nginx-sni-proxy.nix
     ] else [])
     (if (currentSystem == "aarch64-darwin") then [
       inputs.agenix.darwinModules.default
diff --git a/modules/linux/nginx-sni-proxy.nix b/modules/linux/nginx-sni-proxy.nix
@@ -0,0 +1,51 @@
+{ config, lib, ... }:
+
+let
+  cfg = config.services.nginx-sni-proxy;
+  upstreams = with lib; (concatStringsSep "\n" (mapAttrsToList (host: dest:
+      "${host} ${dest}:443;"
+    ) (concatMapAttrs (dest: hosts:
+      (genAttrs hosts (host: dest))
+    ) cfg.upstreamHosts
+  )));
+
+in {
+
+  options.services.nginx-sni-proxy = {
+    enable = lib.mkEnableOption "nginx SNI proxy";
+
+    upstreamHosts = lib.mkOption {
+      type = with lib.types; attrsOf (listOf str);
+      default = {};
+    };
+  };
+
+  config.services.nginx = lib.mkIf cfg.enable {
+    defaultSSLListenPort = 7443;
+    defaultListenAddresses = [ "[::1]" ];
+
+    streamConfig = ''
+      map $ssl_preread_server_name $sni_upstream {
+        ${upstreams}
+        default [::1]:7443;
+      }
+      server {
+        listen 0.0.0.0:443;
+        listen [::]:443;
+        ssl_preread on;
+        resolver 1.1.1.1;
+        proxy_pass $sni_upstream;
+      }
+    '';
+
+    appendHttpConfig = ''
+      server {
+        listen        0.0.0.0:80;
+        listen        [::]:80;
+        server_name   _;
+        return 301 https://$host$request_uri;
+      }
+    '';
+  };
+
+}