@@ -18,22 +18,20 @@ let
1818
1919 mod_perl = pkgs.apacheHttpdPackages.mod_perl.override { apacheHttpd = httpd; };
2020
21− defaultListen = cfg: if cfg.enableSSL
22− then [{ip = "*"; port = 443;}]
23− else [{ip = "*"; port = 80;}];
21+ vhosts = attrValues mainCfg.virtualHosts;
2422
25− getListen = cfg:
26− if cfg.listen == []
27− then defaultListen cfg
28− else cfg.listen;
23+ mkListenInfo = hostOpts:
24+ if hostOpts.listen != [] then hostOpts.listen
25+ else (
26+ optional (hostOpts.onlySSL || hostOpts.addSSL || hostOpts.forceSSL) { ip = "*"; port = 443; ssl = true; } ++
27+ optional (!hostOpts.onlySSL) { ip = "*"; port = 80; ssl = false; }
28+ );
2929
30− listenToString = l: "${l.ip}:${toString l.port}";
30+ listenInfo = unique (concatMap mkListenInfo vhosts);
3131
32− allHosts = [mainCfg] ++ mainCfg.virtualHosts;
32+ enableSSL = any (listen: listen.ssl) listenInfo;
3333
34− enableSSL = any (vhost: vhost.enableSSL) allHosts;
35−
36− enableUserDir = any (vhost: vhost.enableUserDir) allHosts;
34+ enableUserDir = any (vhost: vhost.enableUserDir) vhosts;
3735
3836 # NOTE: generally speaking order of modules is very important
3937 modules =
@@ -115,122 +113,137 @@ let
115113 </IfModule>
116114 '';
117115
118−
119− perServerConf = isMainServer: cfg: let
120−
121− # Canonical name must not include a trailing slash.
122− canonicalNames =
123− let defaultPort = (head (defaultListen cfg)).port; in
124− map (port:
125− (if cfg.enableSSL then "https" else "http") + "://" +
126− cfg.hostName +
127− (if port != defaultPort then ":${toString port}" else "")
128− ) (map (x: x.port) (getListen cfg));
129−
130− maybeDocumentRoot = fold (svc: acc:
131− if acc == null then svc.documentRoot else assert svc.documentRoot == null; acc
132− ) null ([ cfg ]);
133−
134− documentRoot = if maybeDocumentRoot != null then maybeDocumentRoot else
135− pkgs.runCommand "empty" { preferLocalBuild = true; } "mkdir -p $out";
136−
137− documentRootConf = ''
138− DocumentRoot "${documentRoot}"
139−
140− <Directory "${documentRoot}">
141− Options Indexes FollowSymLinks
142− AllowOverride None
143− ${allGranted}
144− </Directory>
145− '';
146−
147− # If this is a vhost, the include the entries for the main server as well.
148− robotsTxt = concatStringsSep "\n" (filter (x: x != "") ([ cfg.robotsEntries ] ++ lib.optional (!isMainServer) mainCfg.robotsEntries));
149−
150− in ''
151− ${concatStringsSep "\n" (map (n: "ServerName ${n}") canonicalNames)}
152−
153− ${concatMapStrings (alias: "ServerAlias ${alias}\n") cfg.serverAliases}
154−
155− ${if cfg.sslServerCert != null then ''
156− SSLCertificateFile ${cfg.sslServerCert}
157− SSLCertificateKeyFile ${cfg.sslServerKey}
158− ${if cfg.sslServerChain != null then ''
159− SSLCertificateChainFile ${cfg.sslServerChain}
160− '' else ""}
161− '' else ""}
162−
163− ${if cfg.enableSSL then ''
164− SSLEngine on
165− '' else if enableSSL then /* i.e., SSL is enabled for some host, but not this one */
166− ''
167− SSLEngine off
168− '' else ""}
169−
170− ${if isMainServer || cfg.adminAddr != null then ''
171− ServerAdmin ${cfg.adminAddr}
172− '' else ""}
173−
174− ${if !isMainServer && mainCfg.logPerVirtualHost then ''
175− ErrorLog ${mainCfg.logDir}/error-${cfg.hostName}.log
176− CustomLog ${mainCfg.logDir}/access-${cfg.hostName}.log ${cfg.logFormat}
177− '' else ""}
178−
179− ${optionalString (robotsTxt != "") ''
180− Alias /robots.txt ${pkgs.writeText "robots.txt" robotsTxt}
181− ''}
182−
183− ${if isMainServer || maybeDocumentRoot != null then documentRootConf else ""}
184−
185− ${if cfg.enableUserDir then ''
186−
187− UserDir public_html
188− UserDir disabled root
189−
190− <Directory "/home/*/public_html">
191− AllowOverride FileInfo AuthConfig Limit Indexes
192− Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
193− <Limit GET POST OPTIONS>
194− ${allGranted}
195− </Limit>
196− <LimitExcept GET POST OPTIONS>
197− ${allDenied}
198− </LimitExcept>
199− </Directory>
200−
201− '' else ""}
202−
203− ${if cfg.globalRedirect != null && cfg.globalRedirect != "" then ''
204− RedirectPermanent / ${cfg.globalRedirect}
205− '' else ""}
206−
207− ${
208− let makeFileConf = elem: ''
209− Alias ${elem.urlPath} ${elem.file}
210− '';
211− in concatMapStrings makeFileConf cfg.servedFiles
212− }
213−
214− ${
215− let makeDirConf = elem: ''
216− Alias ${elem.urlPath} ${elem.dir}/
217− <Directory ${elem.dir}>
218− Options +Indexes
219− ${allGranted}
220− AllowOverride All
221− </Directory>
222− '';
223− in concatMapStrings makeDirConf cfg.servedDirs
224− }
225−
226− ${cfg.extraConfig}
227− '';
116+ mkVHostConf = hostOpts:
117+ let
118+ adminAddr = if hostOpts.adminAddr != null then hostOpts.adminAddr else mainCfg.adminAddr;
119+ listen = filter (listen: !listen.ssl) (mkListenInfo hostOpts);
120+ listenSSL = filter (listen: listen.ssl) (mkListenInfo hostOpts);
121+
122+ useACME = hostOpts.enableACME || hostOpts.useACMEHost != null;
123+ sslCertDir =
124+ if hostOpts.enableACME then config.security.acme.certs.${hostOpts.hostName}.directory
125+ else if hostOpts.useACMEHost != null then config.security.acme.certs.${hostOpts.useACMEHost}.directory
126+ else abort "This case should never happen.";
127+
128+ sslServerCert = if useACME then "${sslCertDir}/full.pem" else hostOpts.sslServerCert;
129+ sslServerKey = if useACME then "${sslCertDir}/key.pem" else hostOpts.sslServerKey;
130+ sslServerChain = if useACME then "${sslCertDir}/fullchain.pem" else hostOpts.sslServerChain;
131+
132+ acmeChallenge = optionalString useACME ''
133+ Alias /.well-known/acme-challenge/ "${hostOpts.acmeRoot}/.well-known/acme-challenge/"
134+ <Directory "${hostOpts.acmeRoot}">
135+ AllowOverride None
136+ Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
137+ Require method GET POST OPTIONS
138+ Require all granted
139+ </Directory>
140+ '';
141+ in
142+ optionalString (listen != []) ''
143+ <VirtualHost ${concatMapStringsSep " " (listen: "${listen.ip}:${toString listen.port}") listen}>
144+ ServerName ${hostOpts.hostName}
145+ ${concatMapStrings (alias: "ServerAlias ${alias}\n") hostOpts.serverAliases}
146+ ServerAdmin ${adminAddr}
147+ <IfModule mod_ssl.c>
148+ SSLEngine off
149+ </IfModule>
150+ ${acmeChallenge}
151+ ${if hostOpts.forceSSL then ''
152+ <IfModule mod_rewrite.c>
153+ RewriteEngine on
154+ RewriteCond %{REQUEST_URI} !^/.well-known/acme-challenge [NC]
155+ RewriteCond %{HTTPS} off
156+ RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
157+ </IfModule>
158+ '' else mkVHostCommonConf hostOpts}
159+ </VirtualHost>
160+ '' +
161+ optionalString (listenSSL != []) ''
162+ <VirtualHost ${concatMapStringsSep " " (listen: "${listen.ip}:${toString listen.port}") listenSSL}>
163+ ServerName ${hostOpts.hostName}
164+ ${concatMapStrings (alias: "ServerAlias ${alias}\n") hostOpts.serverAliases}
165+ ServerAdmin ${adminAddr}
166+ SSLEngine on
167+ SSLCertificateFile ${sslServerCert}
168+ SSLCertificateKeyFile ${sslServerKey}
169+ ${optionalString (sslServerChain != null) "SSLCertificateChainFile ${sslServerChain}"}
170+ ${acmeChallenge}
171+ ${mkVHostCommonConf hostOpts}
172+ </VirtualHost>
173+ ''
174+ ;
175+
176+ mkVHostCommonConf = hostOpts:
177+ let
178+ documentRoot = if hostOpts.documentRoot != null
179+ then hostOpts.documentRoot
180+ else pkgs.runCommand "empty" { preferLocalBuild = true; } "mkdir -p $out"
181+ ;
182+ in
183+ ''
184+ ${optionalString mainCfg.logPerVirtualHost ''
185+ ErrorLog ${mainCfg.logDir}/error-${hostOpts.hostName}.log
186+ CustomLog ${mainCfg.logDir}/access-${hostOpts.hostName}.log ${hostOpts.logFormat}
187+ ''}
188+
189+ ${optionalString (hostOpts.robotsEntries != "") ''
190+ Alias /robots.txt ${pkgs.writeText "robots.txt" hostOpts.robotsEntries}
191+ ''}
192+
193+ DocumentRoot "${documentRoot}"
194+
195+ <Directory "${documentRoot}">
196+ Options Indexes FollowSymLinks
197+ AllowOverride None
198+ ${allGranted}
199+ </Directory>
200+
201+ ${optionalString hostOpts.enableUserDir ''
202+ UserDir public_html
203+ UserDir disabled root
204+ <Directory "/home/*/public_html">
205+ AllowOverride FileInfo AuthConfig Limit Indexes
206+ Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
207+ <Limit GET POST OPTIONS>
208+ Require all granted
209+ </Limit>
210+ <LimitExcept GET POST OPTIONS>
211+ Require all denied
212+ </LimitExcept>
213+ </Directory>
214+ ''}
215+
216+ ${optionalString (hostOpts.globalRedirect != null && hostOpts.globalRedirect != "") ''
217+ RedirectPermanent / ${hostOpts.globalRedirect}
218+ ''}
219+
220+ ${
221+ let makeFileConf = elem: ''
222+ Alias ${elem.urlPath} ${elem.file}
223+ '';
224+ in concatMapStrings makeFileConf hostOpts.servedFiles
225+ }
226+ ${
227+ let makeDirConf = elem: ''
228+ Alias ${elem.urlPath} ${elem.dir}/
229+ <Directory ${elem.dir}>
230+ Options +Indexes
231+ ${allGranted}
232+ AllowOverride All
233+ </Directory>
234+ '';
235+ in concatMapStrings makeDirConf hostOpts.servedDirs
236+ }
237+
238+ ${hostOpts.extraConfig}
239+ ''
240+ ;
228241
229242
230243 confFile = pkgs.writeText "httpd.conf" ''
231244
232245 ServerRoot ${httpd}
233−
246+ ServerName ${config.networking.hostName}
234247 DefaultRuntimeDir ${runtimeDir}/runtime
235248
236249 PidFile ${runtimeDir}/httpd.pid
@@ -246,10 +259,9 @@ let
246259 </IfModule>
247260
248261 ${let
249− listen = concatMap getListen allHosts;
250− toStr = listen: "Listen ${listenToString listen}\n";
251− uniqueListen = uniqList {inputList = map toStr listen;};
252− in concatStrings uniqueListen
262+ toStr = listen: "Listen ${listen.ip}:${toString listen.port} ${if listen.ssl then "https" else "http"}";
263+ uniqueListen = uniqList {inputList = map toStr listenInfo;};
264+ in concatStringsSep "\n" uniqueListen
253265 }
254266
255267 User ${mainCfg.user}
@@ -297,17 +309,9 @@ let
297309 ${allGranted}
298310 </Directory>
299311
300− # Generate directives for the main server.
301− ${perServerConf true mainCfg}
312+ ${mainCfg.extraConfig}
302313
303− ${let
304− makeVirtualHost = vhost: ''
305− <VirtualHost ${concatStringsSep " " (map listenToString (getListen vhost))}>
306− ${perServerConf false vhost}
307− </VirtualHost>
308− '';
309− in concatMapStrings makeVirtualHost mainCfg.virtualHosts
310− }
314+ ${concatMapStringsSep "\n" mkVHostConf vhosts}
311315 '';
312316
313317 # Generate the PHP configuration file. Should probably be factored
@@ -329,6 +333,21 @@ in
329333 imports = [
330334 (mkRemovedOptionModule [ "services" "httpd" "extraSubservices" ] "Most existing subservices have been ported to the NixOS module system. Please update your configuration accordingly.")
331335 (mkRemovedOptionModule [ "services" "httpd" "stateDir" ] "The httpd module now uses /run/httpd as a runtime directory.")
336+
337+ # virtualHosts options
338+ (mkRemovedOptionModule [ "services" "httpd" "documentRoot" ] "Please define a virtual host using `services.httpd.virtualHosts`.")
339+ (mkRemovedOptionModule [ "services" "httpd" "enableSSL" ] "Please define a virtual host using `services.httpd.virtualHosts`.")
340+ (mkRemovedOptionModule [ "services" "httpd" "enableUserDir" ] "Please define a virtual host using `services.httpd.virtualHosts`.")
341+ (mkRemovedOptionModule [ "services" "httpd" "globalRedirect" ] "Please define a virtual host using `services.httpd.virtualHosts`.")
342+ (mkRemovedOptionModule [ "services" "httpd" "hostName" ] "Please define a virtual host using `services.httpd.virtualHosts`.")
343+ (mkRemovedOptionModule [ "services" "httpd" "listen" ] "Please define a virtual host using `services.httpd.virtualHosts`.")
344+ (mkRemovedOptionModule [ "services" "httpd" "robotsEntries" ] "Please define a virtual host using `services.httpd.virtualHosts`.")
345+ (mkRemovedOptionModule [ "services" "httpd" "servedDirs" ] "Please define a virtual host using `services.httpd.virtualHosts`.")
346+ (mkRemovedOptionModule [ "services" "httpd" "servedFiles" ] "Please define a virtual host using `services.httpd.virtualHosts`.")
347+ (mkRemovedOptionModule [ "services" "httpd" "serverAliases" ] "Please define a virtual host using `services.httpd.virtualHosts`.")
348+ (mkRemovedOptionModule [ "services" "httpd" "sslServerCert" ] "Please define a virtual host using `services.httpd.virtualHosts`.")
349+ (mkRemovedOptionModule [ "services" "httpd" "sslServerChain" ] "Please define a virtual host using `services.httpd.virtualHosts`.")
350+ (mkRemovedOptionModule [ "services" "httpd" "sslServerKey" ] "Please define a virtual host using `services.httpd.virtualHosts`.")
332351 ];
333352
334353 ###### interface
@@ -391,9 +410,25 @@ in
391410 '';
392411 };
393412
413+ adminAddr = mkOption {
414+ type = types.str;
415+ example = "admin@example.org";
416+ description = "E-mail address of the server administrator.";
417+ };
418+
419+ logFormat = mkOption {
420+ type = types.str;
421+ default = "common";
422+ example = "combined";
423+ description = ''
424+ Log format for log files. Possible values are: combined, common, referer, agent.
425+ See <link xlink:href="https://httpd.apache.org/docs/2.4/logs.html"/> for more details.
426+ '';
427+ };
428+
394429 logPerVirtualHost = mkOption {
395430 type = types.bool;
396− default = false;
431+ default = true;
397432 description = ''
398433 If enabled, each virtual host gets its own
399434 <filename>access.log</filename> and
@@ -429,26 +464,28 @@ in
429464 };
430465
431466 virtualHosts = mkOption {
432− type = types.listOf (types.submodule (
433− { options = import ./per-server-options.nix {
434− inherit lib;
435− forMainServer = false;
467+ type = with types; attrsOf (submodule (import ./per-server-options.nix));
468+ default = {
469+ localhost = {
470+ documentRoot = "${httpd}/htdocs";
471+ };
472+ };
473+ example = literalExample ''
474+ {
475+ "foo.example.com" = {
476+ forceSSL = true;
477+ documentRoot = "/var/www/foo.example.com"
478+ };
479+ "bar.example.com" = {
480+ addSSL = true;
481+ documentRoot = "/var/www/bar.example.com";
436482 };
437− }));
438− default = [];
439− example = [
440− { hostName = "foo";
441− documentRoot = "/data/webroot-foo";
442− }
443− { hostName = "bar";
444− documentRoot = "/data/webroot-bar";
445483 }
446− ];
484+ '';
447485 description = ''
448− Specification of the virtual hosts served by Apache. Each
486+ Specification of the virtual hosts served by Apache. Each
449487 element should be an attribute set specifying the
450− configuration of the virtual host. The available options
451− are the non-global options permissible for the main host.
488+ configuration of the virtual host.
452489 '';
453490 };
454491
@@ -534,13 +571,7 @@ in
534571 example = "All -SSLv2 -SSLv3";
535572 description = "Allowed SSL/TLS protocol versions.";
536573 };
537− }
538−
539− # Include the options shared between the main server and virtual hosts.
540− // (import ./per-server-options.nix {
541− inherit lib;
542− forMainServer = true;
543− });
574+ };
544575
545576 };
546577
@@ -549,11 +580,31 @@ in
549580
550581 config = mkIf config.services.httpd.enable {
551582
552− assertions = [ { assertion = mainCfg.enableSSL == true
553− -> mainCfg.sslServerCert != null
554− && mainCfg.sslServerKey != null;
555− message = "SSL is enabled for httpd, but sslServerCert and/or sslServerKey haven't been specified."; }
556− ];
583+ assertions = [
584+ {
585+ assertion = all (hostOpts: !hostOpts.enableSSL) vhosts;
586+ message = ''
587+ The option `services.httpd.virtualHosts.<name>.enableSSL` no longer has any effect; please remove it.
588+ Select one of `services.httpd.virtualHosts.<name>.addSSL`, `services.httpd.virtualHosts.<name>.forceSSL`,
589+ or `services.httpd.virtualHosts.<name>.onlySSL`.
590+ '';
591+ }
592+ {
593+ assertion = all (hostOpts: with hostOpts; !(addSSL && onlySSL) && !(forceSSL && onlySSL) && !(addSSL && forceSSL)) vhosts;
594+ message = ''
595+ Options `services.httpd.virtualHosts.<name>.addSSL`,
596+ `services.httpd.virtualHosts.<name>.onlySSL` and `services.httpd.virtualHosts.<name>.forceSSL`
597+ are mutually exclusive.
598+ '';
599+ }
600+ {
601+ assertion = all (hostOpts: !(hostOpts.enableACME && hostOpts.useACMEHost != null)) vhosts;
602+ message = ''
603+ Options `services.httpd.virtualHosts.<name>.enableACME` and
604+ `services.httpd.virtualHosts.<name>.useACMEHost` are mutually exclusive.
605+ '';
606+ }
607+ ];
557608
558609 users.users = optionalAttrs (mainCfg.user == "wwwrun") (singleton
559610 { name = "wwwrun";
@@ -567,6 +618,15 @@ in
567618 gid = config.ids.gids.wwwrun;
568619 });
569620
621+ security.acme.certs = mapAttrs (name: hostOpts: {
622+ user = mainCfg.user;
623+ group = mkDefault mainCfg.group;
624+ email = if hostOpts.adminAddr != null then hostOpts.adminAddr else mainCfg.adminAddr;
625+ webroot = hostOpts.acmeRoot;
626+ extraDomains = genAttrs hostOpts.serverAliases (alias: null);
627+ postRun = "systemctl reload httpd.service";
628+ }) (filterAttrs (name: hostOpts: hostOpts.enableACME) mainCfg.virtualHosts);
629+
570630 environment.systemPackages = [httpd];
571631
572632 services.httpd.phpOptions =
@@ -605,10 +665,14 @@ in
605665 ];
606666
607667 systemd.services.httpd =
668+ let
669+ vhostsACME = filter (hostOpts: hostOpts.enableACME) vhosts;
670+ in
608671 { description = "Apache HTTPD";
609672
610673 wantedBy = [ "multi-user.target" ];
611− after = [ "network.target" "fs.target" ];
674+ wants = concatLists (map (hostOpts: [ "acme-${hostOpts.hostName}.service" "acme-selfsigned-${hostOpts.hostName}.service" ]) vhostsACME);
675+ after = [ "network.target" "fs.target" ] ++ map (hostOpts: "acme-selfsigned-${hostOpts.hostName}.service") vhostsACME;
612676
613677 path =
614678 [ httpd pkgs.coreutils pkgs.gnugrep ]