NixOS module for easily defining Caddy virtual hosts to redirect HTTP requests to a Tailscale service/machine to their HTTPS FQDN
tailscale-redirects.nix
39 lines 1.2 kB view raw
1{ 2 lib, 3 config, 4 ... 5}: let 6 cfg = config.services.tailscale-redirects; 7in { 8 options.services.tailscale-redirects = with lib; { 9 enable = mkEnableOption "tailscale-redirects"; 10 tailnet = mkOption { 11 type = types.str; 12 example = "tail-scale.ts.net"; 13 description = "The [tailnet name](https://tailscale.com/kb/1217/tailnet-name) to use for all redirects."; 14 }; 15 services = mkOption { 16 type = types.listOf types.str; 17 example = ''[ "grafana" "linkwarden" "beszel" ]''; 18 description = "A list of the service names to be given HTTP and shortname redirects to their FQDN HTTPS equivalents."; 19 }; 20 }; 21 22 config = lib.mkIf cfg.enable { 23 assertions = [ 24 { 25 assertion = config.services.caddy.enable; 26 message = "services.tailscale-redirects only works when services.caddy is enabled"; 27 } 28 ]; 29 30 services.caddy.virtualHosts = let 31 redirect = svc: "redir https://${svc}.${cfg.tailnet} 308"; 32 serviceMapping = lib.concatMapAttrs (key: _value: { 33 "http://${key}".extraConfig = redirect key; 34 "http://${key}.${cfg.tailnet}".extraConfig = redirect key; 35 }) (lib.genAttrs cfg.services (svc: null)); 36 in 37 serviceMapping; 38 }; 39}