my nix configs for my servers and desktop
1{lib, pkgs, config, ...}: 2 3/* taken from https://github.com/jdheyburn/nixos-configs 4no license 5*/ 6 7with lib; 8let 9 cfg = config.modules.caddy; 10 caddyMetricsPort = 2019; 11 12 # Generate Caddyfile content from the proxy configuration 13 generateCaddyfile = proxies: 14 let 15 proxyEntries = mapAttrsToList (domain: upstreams: 16 let 17 upstreamList = if isList upstreams then upstreams else [upstreams]; 18 upstreamStr = concatStringsSep " " upstreamList; 19 in '' 20 ${domain} { 21 reverse_proxy ${upstreamStr} 22 23 # Optional: Add some common headers for better proxying 24 header_up Host {upstream_hostport} 25 header_up X-Real-IP {remote_host} 26 header_up X-Forwarded-For {remote_host} 27 header_up X-Forwarded-Proto {scheme} 28 } 29 '') proxies; 30 in 31 concatStringsSep "\n\n" proxyEntries; 32 33in 34{ 35 options = { 36 modules = { 37 caddy = { 38 enable = mkEnableOption "Deploy Caddy"; 39 40 reverseProxies = mkOption { 41 type = types.attrsOf (types.either types.str (types.listOf types.str)); 42 default = {}; 43 description = "Attribute set of domain to upstream mappings for reverse proxying. Upstreams can be a single string or a list of strings for load balancing."; 44 example = { 45 "notes.nekomimi.pet" = "valefar:3009"; 46 "git.nekomimi.pet" = ["morax:3000" "valefar:3000"]; # Load balance between multiple upstreams 47 "api.nekomimi.pet" = ["server1:8080" "server2:8080" "server3:8080"]; 48 }; 49 }; 50 51 extraConfig = mkOption { 52 type = types.lines; 53 default = ""; 54 description = "Extra Caddyfile configuration to append"; 55 }; 56 57 email = mkOption { 58 type = types.nullOr types.str; 59 default = null; 60 description = "Email address for ACME certificate registration"; 61 }; 62 }; 63 }; 64 }; 65 66 config = mkIf cfg.enable { 67 # Allow network access when building 68 # https://mdleom.com/blog/2021/12/27/caddy-plugins-nixos/#xcaddy 69 #nix.settings.sandbox = false; 70 71 networking.firewall.allowedTCPPorts = [ 72 80 73 443 74 caddyMetricsPort 75 ]; 76 77 services.caddy = { 78 enable = true; 79 /*package = pkgs.caddy.withPlugins { 80 plugins = [ "github.com/caddy-dns/cloudflare@v0.2.1"]; 81 hash = "sha256-1niaf801sijvjrqvw998y8x7b43a0g162h3ry530qwl8lrgkapii"; 82 };*/ 83 84 extraConfig = '' 85 ${optionalString (cfg.email != null) '' 86 { 87 email ${cfg.email} 88 } 89 ''} 90 91 ${generateCaddyfile cfg.reverseProxies} 92 93 ${cfg.extraConfig} 94 ''; 95 }; 96 97 systemd.services.caddy = { 98 serviceConfig = { 99 AmbientCapabilities = "cap_net_bind_service"; 100 CapabilityBoundingSet = "cap_net_bind_service"; 101 TimeoutStartSec = "5m"; 102 }; 103 }; 104 }; 105}