git.iko.soy/typeable/nixpkgs
on master help sign in
Merge pull request #73113 from aanderse/httpd-vhost

nixos/httpd: support overridable virtual hosts

commit4d2dd1554618831f0a5b159b8a4dff86612c02a9 authorAaron Andersen <aaron@fosslib.net> dateThu 26 Dec 2019, 08:09 (7 years ago) parentc9a80e779215f0
16 files changed+727−649
nixos/doc/manual/configuration/abstractions.xml+40−95 nixos/doc/manual/configuration/config-file.xml+6−2 nixos/doc/manual/release-notes/rl-2003.xml+22 nixos/modules/services/monitoring/nagios.nix+25−11 nixos/modules/services/web-apps/limesurvey.nix+41−47 nixos/modules/services/web-apps/mediawiki.nix+25−34 nixos/modules/services/web-apps/moodle.nix+24−30 nixos/modules/services/web-apps/wordpress.nix+35−45 nixos/modules/services/web-apps/zabbix.nix+24−30 nixos/modules/services/web-servers/apache-httpd/default.nix+231−167 nixos/modules/services/web-servers/apache-httpd/per-server-options.nix+231−170 nixos/tests/ec2.nix+1−1 nixos/tests/haproxy.nix+8−6 nixos/tests/hitch/default.nix+1−1 nixos/tests/proxy.nix+8−7 nixos/tests/upnp.nix+5−3
nixos/doc/manual/configuration/abstractions.xml+40−95
@@ -11,50 +11,46 @@
1111<programlisting>
1212{
1313 <xref linkend="opt-services.httpd.virtualHosts"/> =
14− [ { hostName = "example.org";
15− documentRoot = "/webroot";
14+ { "blog.example.org" = {
15+ documentRoot = "/webroot/blog.example.org";
1616 adminAddr = "alice@example.org";
17− enableUserDir = true;
18− }
19− { hostName = "example.org";
20− documentRoot = "/webroot";
17+ forceSSL = true;
18+ enableACME = true;
19+ enablePHP = true;
20+ };
21+ "wiki.example.org" = {
22+ documentRoot = "/webroot/wiki.example.org";
2123 adminAddr = "alice@example.org";
22− enableUserDir = true;
23− enableSSL = true;
24− sslServerCert = "/root/ssl-example-org.crt";
25− sslServerKey = "/root/ssl-example-org.key";
26− }
27− ];
24+ forceSSL = true;
25+ enableACME = true;
26+ enablePHP = true;
27+ };
28+ };
2829}
2930</programlisting>
3031 It defines two virtual hosts with nearly identical configuration; the only
31− difference is that the second one has SSL enabled. To prevent this
32+ difference is the document root directories. To prevent this
3233 duplication, we can use a <literal>let</literal>:
3334<programlisting>
3435let
35− exampleOrgCommon =
36− { hostName = "example.org";
37− documentRoot = "/webroot";
38− adminAddr = "alice@example.org";
39− enableUserDir = true;
36+ commonConfig =
37+ { adminAddr = "alice@example.org";
38+ forceSSL = true;
39+ enableACME = true;
4040 };
4141in
4242{
4343 <xref linkend="opt-services.httpd.virtualHosts"/> =
44− [ exampleOrgCommon
45− (exampleOrgCommon // {
46− enableSSL = true;
47− sslServerCert = "/root/ssl-example-org.crt";
48− sslServerKey = "/root/ssl-example-org.key";
49− })
50− ];
44+ { "blog.example.org" = (commonConfig // { documentRoot = "/webroot/blog.example.org"; });
45+ "wiki.example.org" = (commonConfig // { documentRoot = "/webroot/wiki.example.com"; });
46+ };
5147}
5248</programlisting>
53− The <literal>let exampleOrgCommon = <replaceable>...</replaceable></literal>
54− defines a variable named <literal>exampleOrgCommon</literal>. The
49+ The <literal>let commonConfig = <replaceable>...</replaceable></literal>
50+ defines a variable named <literal>commonConfig</literal>. The
5551 <literal>//</literal> operator merges two attribute sets, so the
5652 configuration of the second virtual host is the set
57− <literal>exampleOrgCommon</literal> extended with the SSL options.
53+ <literal>commonConfig</literal> extended with the document root option.
5854 </para>
5955
6056 <para>
@@ -63,13 +59,13 @@ in
6359<programlisting>
6460{
6561 <xref linkend="opt-services.httpd.virtualHosts"/> =
66− let exampleOrgCommon = <replaceable>...</replaceable>; in
67− [ exampleOrgCommon
68− (exampleOrgCommon // { <replaceable>...</replaceable> })
69− ];
62+ let commonConfig = <replaceable>...</replaceable>; in
63+ { "blog.example.org" = (commonConfig // { <replaceable>...</replaceable> })
64+ "wiki.example.org" = (commonConfig // { <replaceable>...</replaceable> })
65+ };
7066}
7167</programlisting>
72− but not <literal>{ let exampleOrgCommon = <replaceable>...</replaceable>; in
68+ but not <literal>{ let commonConfig = <replaceable>...</replaceable>; in
7369 <replaceable>...</replaceable>; }</literal> since attributes (as opposed to
7470 attribute values) are not expressions.
7571 </para>
@@ -77,80 +73,29 @@ in
7773 <para>
7874 <emphasis>Functions</emphasis> provide another method of abstraction. For
7975 instance, suppose that we want to generate lots of different virtual hosts,
80− all with identical configuration except for the host name. This can be done
76+ all with identical configuration except for the document root. This can be done
8177 as follows:
8278<programlisting>
8379{
8480 <xref linkend="opt-services.httpd.virtualHosts"/> =
8581 let
86− makeVirtualHost = name:
87− { hostName = name;
88− documentRoot = "/webroot";
82+ makeVirtualHost = webroot:
83+ { documentRoot = webroot;
8984 adminAddr = "alice@example.org";
85+ forceSSL = true;
86+ enableACME = true;
9087 };
9188 in
92− [ (makeVirtualHost "example.org")
93− (makeVirtualHost "example.com")
94− (makeVirtualHost "example.gov")
95− (makeVirtualHost "example.nl")
96− ];
89+ { "example.org" = (makeVirtualHost "/webroot/example.org");
90+ "example.com" = (makeVirtualHost "/webroot/example.com");
91+ "example.gov" = (makeVirtualHost "/webroot/example.gov");
92+ "example.nl" = (makeVirtualHost "/webroot/example.nl");
93+ };
9794}
9895</programlisting>
9996 Here, <varname>makeVirtualHost</varname> is a function that takes a single
100− argument <literal>name</literal> and returns the configuration for a virtual
97+ argument <literal>webroot</literal> and returns the configuration for a virtual
10198 host. That function is then called for several names to produce the list of
10299 virtual host configurations.
103100 </para>
104−
105− <para>
106− We can further improve on this by using the function <varname>map</varname>,
107− which applies another function to every element in a list:
108−<programlisting>
109−{
110− <xref linkend="opt-services.httpd.virtualHosts"/> =
111− let
112− makeVirtualHost = <replaceable>...</replaceable>;
113− in map makeVirtualHost
114− [ "example.org" "example.com" "example.gov" "example.nl" ];
115−}
116−</programlisting>
117− (The function <literal>map</literal> is called a <emphasis>higher-order
118− function</emphasis> because it takes another function as an argument.)
119− </para>
120−
121− <para>
122− What if you need more than one argument, for instance, if we want to use a
123− different <literal>documentRoot</literal> for each virtual host? Then we can
124− make <varname>makeVirtualHost</varname> a function that takes a
125− <emphasis>set</emphasis> as its argument, like this:
126−<programlisting>
127−{
128− <xref linkend="opt-services.httpd.virtualHosts"/> =
129− let
130− makeVirtualHost = { name, root }:
131− { hostName = name;
132− documentRoot = root;
133− adminAddr = "alice@example.org";
134− };
135− in map makeVirtualHost
136− [ { name = "example.org"; root = "/sites/example.org"; }
137− { name = "example.com"; root = "/sites/example.com"; }
138− { name = "example.gov"; root = "/sites/example.gov"; }
139− { name = "example.nl"; root = "/sites/example.nl"; }
140− ];
141−}
142−</programlisting>
143− But in this case (where every root is a subdirectory of
144− <filename>/sites</filename> named after the virtual host), it would have been
145− shorter to define <varname>makeVirtualHost</varname> as
146−<programlisting>
147−makeVirtualHost = name:
148− { hostName = name;
149− documentRoot = "/sites/${name}";
150− adminAddr = "alice@example.org";
151− };
152−</programlisting>
153− Here, the construct <literal>${<replaceable>...</replaceable>}</literal>
154− allows the result of an expression to be spliced into a string.
155− </para>
156101</section>
nixos/doc/manual/configuration/config-file.xml+6−2
@@ -27,7 +27,7 @@
2727
2828{ <xref linkend="opt-services.httpd.enable"/> = true;
2929 <xref linkend="opt-services.httpd.adminAddr"/> = "alice@example.org";
30− <xref linkend="opt-services.httpd.documentRoot"/> = "/webroot";
30+ <link linkend="opt-services.httpd.virtualHosts">services.httpd.virtualHosts.localhost.documentRoot</link> = "/webroot";
3131}
3232</programlisting>
3333 defines a configuration with three option definitions that together enable
@@ -50,7 +50,11 @@
5050 httpd = {
5151 enable = true;
5252 adminAddr = "alice@example.org";
53− documentRoot = "/webroot";
53+ virtualHosts = {
54+ localhost = {
55+ documentRoot = "/webroot";
56+ };
57+ };
5458 };
5559 };
5660}
nixos/doc/manual/release-notes/rl-2003.xml+22
@@ -327,6 +327,28 @@ services.xserver.displayManager.defaultSession = "xfce+icewm";
327327 module.
328328 </para>
329329 </listitem>
330+ <listitem>
331+ <para>
332+ The httpd module no longer provides options to support serving web content without defining a virtual host. As a
333+ result of this the <link linkend="opt-services.httpd.logPerVirtualHost">services.httpd.logPerVirtualHost</link>
334+ option now defaults to <literal>true</literal> instead of <literal>false</literal>. Please update your
335+ configuration to make use of <link linkend="opt-services.httpd.virtualHosts">services.httpd.virtualHosts</link>.
336+ </para>
337+ <para>
338+ The <link linkend="opt-services.httpd.virtualHosts">services.httpd.virtualHosts.&lt;name&gt;</link>
339+ option has changed type from a list of submodules to an attribute set of submodules, better matching
340+ <link linkend="opt-services.nginx.virtualHosts">services.nginx.virtualHosts.&lt;name&gt;</link>.
341+ </para>
342+ <para>
343+ This change comes with the addition of the following options which mimic the functionality of their <literal>nginx</literal> counterparts:
344+ <link linkend="opt-services.httpd.virtualHosts">services.httpd.virtualHosts.&lt;name&gt;.addSSL</link>,
345+ <link linkend="opt-services.httpd.virtualHosts">services.httpd.virtualHosts.&lt;name&gt;.forceSSL</link>,
346+ <link linkend="opt-services.httpd.virtualHosts">services.httpd.virtualHosts.&lt;name&gt;.onlySSL</link>,
347+ <link linkend="opt-services.httpd.virtualHosts">services.httpd.virtualHosts.&lt;name&gt;.enableACME</link>,
348+ <link linkend="opt-services.httpd.virtualHosts">services.httpd.virtualHosts.&lt;name&gt;.acmeRoot</link>, and
349+ <link linkend="opt-services.httpd.virtualHosts">services.httpd.virtualHosts.&lt;name&gt;.useACMEHost</link>.
350+ </para>
351+ </listitem>
330352 </itemizedlist>
331353 </section>
332354
nixos/modules/services/monitoring/nagios.nix+25−11
@@ -8,6 +8,7 @@ let
88
99 nagiosState = "/var/lib/nagios";
1010 nagiosLogDir = "/var/log/nagios";
11+ urlPath = "/nagios";
1112
1213 nagiosObjectDefs = cfg.objectDefs;
1314
@@ -49,12 +50,12 @@ let
4950 ''
5051 main_config_file=${cfg.mainConfigFile}
5152 use_authentication=0
52− url_html_path=${cfg.urlPath}
53+ url_html_path=${urlPath}
5354 '';
5455
5556 extraHttpdConfig =
5657 ''
57− ScriptAlias ${cfg.urlPath}/cgi-bin ${pkgs.nagios}/sbin
58+ ScriptAlias ${urlPath}/cgi-bin ${pkgs.nagios}/sbin
5859
5960 <Directory "${pkgs.nagios}/sbin">
6061 Options ExecCGI
@@ -62,7 +63,7 @@ let
6263 SetEnv NAGIOS_CGI_CONFIG ${cfg.cgiConfigFile}
6364 </Directory>
6465
65− Alias ${cfg.urlPath} ${pkgs.nagios}/share
66+ Alias ${urlPath} ${pkgs.nagios}/share
6667
6768 <Directory "${pkgs.nagios}/share">
6869 Options None
@@ -72,6 +73,10 @@ let
7273
7374in
7475{
76+ imports = [
77+ (mkRemovedOptionModule [ "services" "nagios" "urlPath" ] "The urlPath option has been removed as it is hard coded to /nagios in the nagios package.")
78+ ];
79+
7580 options = {
7681 services.nagios = {
7782 enable = mkOption {
@@ -128,13 +133,20 @@ in
128133 ";
129134 };
130135
131− urlPath = mkOption {
132− default = "/nagios";
133− description = "
134− The URL path under which the Nagios web interface appears.
135− That is, you can access the Nagios web interface through
136− <literal>http://<replaceable>server</replaceable>/<replaceable>urlPath</replaceable></literal>.
137− ";
136+ virtualHost = mkOption {
137+ type = types.submodule (import ../web-servers/apache-httpd/per-server-options.nix);
138+ example = literalExample ''
139+ { hostName = "example.org";
140+ adminAddr = "webmaster@example.org";
141+ enableSSL = true;
142+ sslServerCert = "/var/lib/acme/example.org/full.pem";
143+ sslServerKey = "/var/lib/acme/example.org/key.pem";
144+ }
145+ '';
146+ description = ''
147+ Apache configuration can be done by adapting <option>services.httpd.virtualHosts</option>.
148+ See <xref linkend="opt-services.httpd.virtualHosts"/> for further information.
149+ '';
138150 };
139151 };
140152 };
@@ -182,6 +194,8 @@ in
182194 '';
183195 };
184196
185− services.httpd.extraConfig = optionalString cfg.enableWebInterface extraHttpdConfig;
197+ services.httpd.virtualHosts = optionalAttrs cfg.enableWebInterface {
198+ ${cfg.virtualHost.hostName} = mkMerge [ cfg.virtualHost { extraConfig = extraHttpdConfig; } ];
199+ };
186200 };
187201}
nixos/modules/services/web-apps/limesurvey.nix+41−47
@@ -3,7 +3,7 @@
33let
44
55 inherit (lib) mkDefault mkEnableOption mkForce mkIf mkMerge mkOption;
6− inherit (lib) mapAttrs optional optionalString types;
6+ inherit (lib) literalExample mapAttrs optional optionalString types;
77
88 cfg = config.services.limesurvey;
99 fpm = config.services.phpfpm.pools.limesurvey;
@@ -100,19 +100,15 @@ in
100100 };
101101
102102 virtualHost = mkOption {
103− type = types.submodule ({
104− options = import ../web-servers/apache-httpd/per-server-options.nix {
105− inherit lib;
106− forMainServer = false;
107− };
108− });
109− example = {
110− hostName = "survey.example.org";
111− enableSSL = true;
112− adminAddr = "webmaster@example.org";
113− sslServerCert = "/var/lib/acme/survey.example.org/full.pem";
114− sslServerKey = "/var/lib/acme/survey.example.org/key.pem";
115− };
103+ type = types.submodule (import ../web-servers/apache-httpd/per-server-options.nix);
104+ example = literalExample ''
105+ {
106+ hostName = "survey.example.org";
107+ adminAddr = "webmaster@example.org";
108+ forceSSL = true;
109+ enableACME = true;
110+ }
111+ '';
116112 description = ''
117113 Apache configuration can be done by adapting <literal>services.httpd.virtualHosts.&lt;name&gt;</literal>.
118114 See <xref linkend="opt-services.httpd.virtualHosts"/> for further information.
@@ -184,7 +180,7 @@ in
184180 config = {
185181 tempdir = "${stateDir}/tmp";
186182 uploaddir = "${stateDir}/upload";
187− force_ssl = mkIf cfg.virtualHost.enableSSL "on";
183+ force_ssl = mkIf (cfg.virtualHost.addSSL || cfg.virtualHost.forceSSL || cfg.virtualHost.onlySSL) "on";
188184 config.defaultlang = "en";
189185 };
190186 };
@@ -215,38 +211,36 @@ in
215211 enable = true;
216212 adminAddr = mkDefault cfg.virtualHost.adminAddr;
217213 extraModules = [ "proxy_fcgi" ];
218− virtualHosts = [ (mkMerge [
219− cfg.virtualHost {
220− documentRoot = mkForce "${pkg}/share/limesurvey";
221− extraConfig = ''
222− Alias "/tmp" "${stateDir}/tmp"
223− <Directory "${stateDir}">
224− AllowOverride all
225− Require all granted
226− Options -Indexes +FollowSymlinks
227− </Directory>
228−
229− Alias "/upload" "${stateDir}/upload"
230− <Directory "${stateDir}/upload">
231− AllowOverride all
232− Require all granted
233− Options -Indexes
234− </Directory>
235−
236− <Directory "${pkg}/share/limesurvey">
237− <FilesMatch "\.php$">
238− <If "-f %{REQUEST_FILENAME}">
239− SetHandler "proxy:unix:${fpm.socket}|fcgi://localhost/"
240− </If>
241− </FilesMatch>
242−
243− AllowOverride all
244− Options -Indexes
245− DirectoryIndex index.php
246− </Directory>
247− '';
248− }
249− ]) ];
214+ virtualHosts.${cfg.virtualHost.hostName} = mkMerge [ cfg.virtualHost {
215+ documentRoot = mkForce "${pkg}/share/limesurvey";
216+ extraConfig = ''
217+ Alias "/tmp" "${stateDir}/tmp"
218+ <Directory "${stateDir}">
219+ AllowOverride all
220+ Require all granted
221+ Options -Indexes +FollowSymlinks
222+ </Directory>
223+
224+ Alias "/upload" "${stateDir}/upload"
225+ <Directory "${stateDir}/upload">
226+ AllowOverride all
227+ Require all granted
228+ Options -Indexes
229+ </Directory>
230+
231+ <Directory "${pkg}/share/limesurvey">
232+ <FilesMatch "\.php$">
233+ <If "-f %{REQUEST_FILENAME}">
234+ SetHandler "proxy:unix:${fpm.socket}|fcgi://localhost/"
235+ </If>
236+ </FilesMatch>
237+
238+ AllowOverride all
239+ Options -Indexes
240+ DirectoryIndex index.php
241+ </Directory>
242+ '';
243+ } ];
250244 };
251245
252246 systemd.tmpfiles.rules = [
nixos/modules/services/web-apps/mediawiki.nix+25−34
@@ -64,7 +64,7 @@ let
6464 $wgScriptPath = "";
6565
6666 ## The protocol and server name to use in fully-qualified URLs
67− $wgServer = "${if cfg.virtualHost.enableSSL then "https" else "http"}://${cfg.virtualHost.hostName}";
67+ $wgServer = "${if cfg.virtualHost.addSSL || cfg.virtualHost.forceSSL || cfg.virtualHost.onlySSL then "https" else "http"}://${cfg.virtualHost.hostName}";
6868
6969 ## The URL path to static resources (images, scripts, etc.)
7070 $wgResourceBasePath = $wgScriptPath;
@@ -290,19 +290,13 @@ in
290290 };
291291
292292 virtualHost = mkOption {
293− type = types.submodule ({
294− options = import ../web-servers/apache-httpd/per-server-options.nix {
295− inherit lib;
296− forMainServer = false;
297− };
298− });
293+ type = types.submodule (import ../web-servers/apache-httpd/per-server-options.nix);
299294 example = literalExample ''
300295 {
301296 hostName = "mediawiki.example.org";
302− enableSSL = true;
303297 adminAddr = "webmaster@example.org";
304− sslServerCert = "/var/lib/acme/mediawiki.example.org/full.pem";
305− sslServerKey = "/var/lib/acme/mediawiki.example.org/key.pem";
298+ forceSSL = true;
299+ enableACME = true;
306300 }
307301 '';
308302 description = ''
@@ -389,31 +383,28 @@ in
389383
390384 services.httpd = {
391385 enable = true;
392− adminAddr = mkDefault cfg.virtualHost.adminAddr;
393386 extraModules = [ "proxy_fcgi" ];
394− virtualHosts = [ (mkMerge [
395− cfg.virtualHost {
396− documentRoot = mkForce "${pkg}/share/mediawiki";
397− extraConfig = ''
398− <Directory "${pkg}/share/mediawiki">
399− <FilesMatch "\.php$">
400− <If "-f %{REQUEST_FILENAME}">
401− SetHandler "proxy:unix:${fpm.socket}|fcgi://localhost/"
402− </If>
403− </FilesMatch>
404−
405− Require all granted
406− DirectoryIndex index.php
407− AllowOverride All
408− </Directory>
409− '' + optionalString (cfg.uploadsDir != null) ''
410− Alias "/images" "${cfg.uploadsDir}"
411− <Directory "${cfg.uploadsDir}">
412− Require all granted
413− </Directory>
414− '';
415− }
416− ]) ];
387+ virtualHosts.${cfg.virtualHost.hostName} = mkMerge [ cfg.virtualHost {
388+ documentRoot = mkForce "${pkg}/share/mediawiki";
389+ extraConfig = ''
390+ <Directory "${pkg}/share/mediawiki">
391+ <FilesMatch "\.php$">
392+ <If "-f %{REQUEST_FILENAME}">
393+ SetHandler "proxy:unix:${fpm.socket}|fcgi://localhost/"
394+ </If>
395+ </FilesMatch>
396+
397+ Require all granted
398+ DirectoryIndex index.php
399+ AllowOverride All
400+ </Directory>
401+ '' + optionalString (cfg.uploadsDir != null) ''
402+ Alias "/images" "${cfg.uploadsDir}"
403+ <Directory "${cfg.uploadsDir}">
404+ Require all granted
405+ </Directory>
406+ '';
407+ } ];
417408 };
418409
419410 systemd.tmpfiles.rules = [
nixos/modules/services/web-apps/moodle.nix+24−30
@@ -32,7 +32,7 @@ let
3232 'dbcollation' => 'utf8mb4_unicode_ci',
3333 );
3434
35− $CFG->wwwroot = '${if cfg.virtualHost.enableSSL then "https" else "http"}://${cfg.virtualHost.hostName}';
35+ $CFG->wwwroot = '${if cfg.virtualHost.addSSL || cfg.virtualHost.forceSSL || cfg.virtualHost.onlySSL then "https" else "http"}://${cfg.virtualHost.hostName}';
3636 $CFG->dataroot = '${stateDir}';
3737 $CFG->admin = 'admin';
3838
@@ -140,19 +140,15 @@ in
140140 };
141141
142142 virtualHost = mkOption {
143− type = types.submodule ({
144− options = import ../web-servers/apache-httpd/per-server-options.nix {
145− inherit lib;
146− forMainServer = false;
147− };
148− });
149− example = {
150− hostName = "moodle.example.org";
151− enableSSL = true;
152− adminAddr = "webmaster@example.org";
153− sslServerCert = "/var/lib/acme/moodle.example.org/full.pem";
154− sslServerKey = "/var/lib/acme/moodle.example.org/key.pem";
155− };
143+ type = types.submodule (import ../web-servers/apache-httpd/per-server-options.nix);
144+ example = literalExample ''
145+ {
146+ hostName = "moodle.example.org";
147+ adminAddr = "webmaster@example.org";
148+ forceSSL = true;
149+ enableACME = true;
150+ }
151+ '';
156152 description = ''
157153 Apache configuration can be done by adapting <option>services.httpd.virtualHosts</option>.
158154 See <xref linkend="opt-services.httpd.virtualHosts"/> for further information.
@@ -241,22 +237,20 @@ in
241237 enable = true;
242238 adminAddr = mkDefault cfg.virtualHost.adminAddr;
243239 extraModules = [ "proxy_fcgi" ];
244− virtualHosts = [ (mkMerge [
245− cfg.virtualHost {
246− documentRoot = mkForce "${cfg.package}/share/moodle";
247− extraConfig = ''
248− <Directory "${cfg.package}/share/moodle">
249− <FilesMatch "\.php$">
250− <If "-f %{REQUEST_FILENAME}">
251− SetHandler "proxy:unix:${fpm.socket}|fcgi://localhost/"
252− </If>
253− </FilesMatch>
254− Options -Indexes
255− DirectoryIndex index.php
256− </Directory>
257− '';
258− }
259− ]) ];
240+ virtualHosts.${cfg.virtualHost.hostName} = mkMerge [ cfg.virtualHost {
241+ documentRoot = mkForce "${cfg.package}/share/moodle";
242+ extraConfig = ''
243+ <Directory "${cfg.package}/share/moodle">
244+ <FilesMatch "\.php$">
245+ <If "-f %{REQUEST_FILENAME}">
246+ SetHandler "proxy:unix:${fpm.socket}|fcgi://localhost/"
247+ </If>
248+ </FilesMatch>
249+ Options -Indexes
250+ DirectoryIndex index.php
251+ </Directory>
252+ '';
253+ } ];
260254 };
261255
262256 systemd.tmpfiles.rules = [
nixos/modules/services/web-apps/wordpress.nix+35−45
@@ -3,7 +3,7 @@
33let
44 inherit (lib) mkDefault mkEnableOption mkForce mkIf mkMerge mkOption types;
55 inherit (lib) any attrValues concatMapStringsSep flatten literalExample;
6− inherit (lib) mapAttrs' mapAttrsToList nameValuePair optional optionalAttrs optionalString;
6+ inherit (lib) mapAttrs mapAttrs' mapAttrsToList nameValuePair optional optionalAttrs optionalString;
77
88 eachSite = config.services.wordpress;
99 user = "wordpress";
@@ -209,18 +209,12 @@ let
209209 };
210210
211211 virtualHost = mkOption {
212− type = types.submodule ({
213− options = import ../web-servers/apache-httpd/per-server-options.nix {
214− inherit lib;
215− forMainServer = false;
216− };
217− });
212+ type = types.submodule (import ../web-servers/apache-httpd/per-server-options.nix);
218213 example = literalExample ''
219214 {
220− enableSSL = true;
221215 adminAddr = "webmaster@example.org";
222− sslServerCert = "/var/lib/acme/wordpress.example.org/full.pem";
223− sslServerKey = "/var/lib/acme/wordpress.example.org/key.pem";
216+ forceSSL = true;
217+ enableACME = true;
224218 }
225219 '';
226220 description = ''
@@ -304,41 +298,37 @@ in
304298 services.httpd = {
305299 enable = true;
306300 extraModules = [ "proxy_fcgi" ];
307− virtualHosts = mapAttrsToList (hostName: cfg:
308− (mkMerge [
309− cfg.virtualHost {
310− documentRoot = mkForce "${pkg hostName cfg}/share/wordpress";
311− extraConfig = ''
312− <Directory "${pkg hostName cfg}/share/wordpress">
313− <FilesMatch "\.php$">
314− <If "-f %{REQUEST_FILENAME}">
315− SetHandler "proxy:unix:${config.services.phpfpm.pools."wordpress-${hostName}".socket}|fcgi://localhost/"
316− </If>
317− </FilesMatch>
318−
319− # standard wordpress .htaccess contents
320− <IfModule mod_rewrite.c>
321− RewriteEngine On
322− RewriteBase /
323− RewriteRule ^index\.php$ - [L]
324− RewriteCond %{REQUEST_FILENAME} !-f
325− RewriteCond %{REQUEST_FILENAME} !-d
326− RewriteRule . /index.php [L]
327− </IfModule>
328−
329− DirectoryIndex index.php
330− Require all granted
331− Options +FollowSymLinks
332− </Directory>
333−
334− # https://wordpress.org/support/article/hardening-wordpress/#securing-wp-config-php
335− <Files wp-config.php>
336− Require all denied
337− </Files>
338− '';
339− }
340− ])
341− ) eachSite;
301+ virtualHosts = mapAttrs (hostName: cfg: mkMerge [ cfg.virtualHost {
302+ documentRoot = mkForce "${pkg hostName cfg}/share/wordpress";
303+ extraConfig = ''
304+ <Directory "${pkg hostName cfg}/share/wordpress">
305+ <FilesMatch "\.php$">
306+ <If "-f %{REQUEST_FILENAME}">
307+ SetHandler "proxy:unix:${config.services.phpfpm.pools."wordpress-${hostName}".socket}|fcgi://localhost/"
308+ </If>
309+ </FilesMatch>
310+
311+ # standard wordpress .htaccess contents
312+ <IfModule mod_rewrite.c>
313+ RewriteEngine On
314+ RewriteBase /
315+ RewriteRule ^index\.php$ - [L]
316+ RewriteCond %{REQUEST_FILENAME} !-f
317+ RewriteCond %{REQUEST_FILENAME} !-d
318+ RewriteRule . /index.php [L]
319+ </IfModule>
320+
321+ DirectoryIndex index.php
322+ Require all granted
323+ Options +FollowSymLinks
324+ </Directory>
325+
326+ # https://wordpress.org/support/article/hardening-wordpress/#securing-wp-config-php
327+ <Files wp-config.php>
328+ Require all denied
329+ </Files>
330+ '';
331+ } ]) eachSite;
342332 };
343333
344334 systemd.tmpfiles.rules = flatten (mapAttrsToList (hostName: cfg: [
nixos/modules/services/web-apps/zabbix.nix+24−30
@@ -113,19 +113,15 @@ in
113113 };
114114
115115 virtualHost = mkOption {
116− type = types.submodule ({
117− options = import ../web-servers/apache-httpd/per-server-options.nix {
118− inherit lib;
119− forMainServer = false;
120− };
121− });
122− example = {
123− hostName = "zabbix.example.org";
124− enableSSL = true;
125− adminAddr = "webmaster@example.org";
126− sslServerCert = "/var/lib/acme/zabbix.example.org/full.pem";
127− sslServerKey = "/var/lib/acme/zabbix.example.org/key.pem";
128− };
116+ type = types.submodule (import ../web-servers/apache-httpd/per-server-options.nix);
117+ example = literalExample ''
118+ {
119+ hostName = "zabbix.example.org";
120+ adminAddr = "webmaster@example.org";
121+ forceSSL = true;
122+ enableACME = true;
123+ }
124+ '';
129125 description = ''
130126 Apache configuration can be done by adapting <literal>services.httpd.virtualHosts.&lt;name&gt;</literal>.
131127 See <xref linkend="opt-services.httpd.virtualHosts"/> for further information.
@@ -190,23 +186,21 @@ in
190186 enable = true;
191187 adminAddr = mkDefault cfg.virtualHost.adminAddr;
192188 extraModules = [ "proxy_fcgi" ];
193− virtualHosts = [ (mkMerge [
194− cfg.virtualHost {
195− documentRoot = mkForce "${cfg.package}/share/zabbix";
196− extraConfig = ''
197− <Directory "${cfg.package}/share/zabbix">
198− <FilesMatch "\.php$">
199− <If "-f %{REQUEST_FILENAME}">
200− SetHandler "proxy:unix:${fpm.socket}|fcgi://localhost/"
201− </If>
202− </FilesMatch>
203− AllowOverride all
204− Options -Indexes
205− DirectoryIndex index.php
206− </Directory>
207− '';
208− }
209− ]) ];
189+ virtualHosts.${cfg.virtualHost.hostName} = mkMerge [ cfg.virtualHost {
190+ documentRoot = mkForce "${cfg.package}/share/zabbix";
191+ extraConfig = ''
192+ <Directory "${cfg.package}/share/zabbix">
193+ <FilesMatch "\.php$">
194+ <If "-f %{REQUEST_FILENAME}">
195+ SetHandler "proxy:unix:${fpm.socket}|fcgi://localhost/"
196+ </If>
197+ </FilesMatch>
198+ AllowOverride all
199+ Options -Indexes
200+ DirectoryIndex index.php
201+ </Directory>
202+ '';
203+ } ];
210204 };
211205
212206 users.users.${user} = mapAttrs (name: mkDefault) {
nixos/modules/services/web-servers/apache-httpd/default.nix+231−167
@@ -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 ]
nixos/modules/services/web-servers/apache-httpd/per-server-options.nix+231−170
@@ -1,174 +1,235 @@
1−# This file defines the options that can be used both for the Apache
2−# main server configuration, and for the virtual hosts. (The latter
3−# has additional options that affect the web server as a whole, like
4−# the user/group to run under.)
5−
6−{ forMainServer, lib }:
7−
8−with lib;
9−
1+{ config, lib, name, ... }:
2+let
3+ inherit (lib) mkOption types;
4+in
105{
6+ options = {
7+
8+ hostName = mkOption {
9+ type = types.str;
10+ default = name;
11+ description = "Canonical hostname for the server.";
12+ };
13+
14+ serverAliases = mkOption {
15+ type = types.listOf types.str;
16+ default = [];
17+ example = ["www.example.org" "www.example.org:8080" "example.org"];
18+ description = ''
19+ Additional names of virtual hosts served by this virtual host configuration.
20+ '';
21+ };
22+
23+ listen = mkOption {
24+ type = with types; listOf (submodule ({
25+ options = {
26+ port = mkOption {
27+ type = types.port;
28+ description = "Port to listen on";
29+ };
30+ ip = mkOption {
31+ type = types.str;
32+ default = "*";
33+ description = "IP to listen on. 0.0.0.0 for IPv4 only, * for all.";
34+ };
35+ ssl = mkOption {
36+ type = types.bool;
37+ default = false;
38+ description = "Whether to enable SSL (https) support.";
39+ };
40+ };
41+ }));
42+ default = [];
43+ example = [
44+ { ip = "195.154.1.1"; port = 443; ssl = true;}
45+ { ip = "192.154.1.1"; port = 80; }
46+ { ip = "*"; port = 8080; }
47+ ];
48+ description = ''
49+ Listen addresses and ports for this virtual host.
50+ <note><para>
51+ This option overrides <literal>addSSL</literal>, <literal>forceSSL</literal> and <literal>onlySSL</literal>.
52+ </para></note>
53+ '';
54+ };
55+
56+ enableSSL = mkOption {
57+ type = types.bool;
58+ visible = false;
59+ default = false;
60+ };
61+
62+ addSSL = mkOption {
63+ type = types.bool;
64+ default = false;
65+ description = ''
66+ Whether to enable HTTPS in addition to plain HTTP. This will set defaults for
67+ <literal>listen</literal> to listen on all interfaces on the respective default
68+ ports (80, 443).
69+ '';
70+ };
71+
72+ onlySSL = mkOption {
73+ type = types.bool;
74+ default = false;
75+ description = ''
76+ Whether to enable HTTPS and reject plain HTTP connections. This will set
77+ defaults for <literal>listen</literal> to listen on all interfaces on port 443.
78+ '';
79+ };
80+
81+ forceSSL = mkOption {
82+ type = types.bool;
83+ default = false;
84+ description = ''
85+ Whether to add a separate nginx server block that permanently redirects (301)
86+ all plain HTTP traffic to HTTPS. This will set defaults for
87+ <literal>listen</literal> to listen on all interfaces on the respective default
88+ ports (80, 443), where the non-SSL listens are used for the redirect vhosts.
89+ '';
90+ };
91+
92+ enableACME = mkOption {
93+ type = types.bool;
94+ default = false;
95+ description = ''
96+ Whether to ask Let's Encrypt to sign a certificate for this vhost.
97+ Alternately, you can use an existing certificate through <option>useACMEHost</option>.
98+ '';
99+ };
100+
101+ useACMEHost = mkOption {
102+ type = types.nullOr types.str;
103+ default = null;
104+ description = ''
105+ A host of an existing Let's Encrypt certificate to use.
106+ This is useful if you have many subdomains and want to avoid hitting the
107+ <link xlink:href="https://letsencrypt.org/docs/rate-limits/">rate limit</link>.
108+ Alternately, you can generate a certificate through <option>enableACME</option>.
109+ <emphasis>Note that this option does not create any certificates, nor it does add subdomains to existing ones – you will need to create them manually using <xref linkend="opt-security.acme.certs"/>.</emphasis>
110+ '';
111+ };
112+
113+ acmeRoot = mkOption {
114+ type = types.str;
115+ default = "/var/lib/acme/acme-challenges";
116+ description = "Directory for the acme challenge which is PUBLIC, don't put certs or keys in here";
117+ };
118+
119+ sslServerCert = mkOption {
120+ type = types.path;
121+ example = "/var/host.cert";
122+ description = "Path to server SSL certificate.";
123+ };
124+
125+ sslServerKey = mkOption {
126+ type = types.path;
127+ example = "/var/host.key";
128+ description = "Path to server SSL certificate key.";
129+ };
130+
131+ sslServerChain = mkOption {
132+ type = types.nullOr types.path;
133+ default = null;
134+ example = "/var/ca.pem";
135+ description = "Path to server SSL chain file.";
136+ };
137+
138+ adminAddr = mkOption {
139+ type = types.nullOr types.str;
140+ default = null;
141+ example = "admin@example.org";
142+ description = "E-mail address of the server administrator.";
143+ };
144+
145+ documentRoot = mkOption {
146+ type = types.nullOr types.path;
147+ default = null;
148+ example = "/data/webserver/docs";
149+ description = ''
150+ The path of Apache's document root directory. If left undefined,
151+ an empty directory in the Nix store will be used as root.
152+ '';
153+ };
154+
155+ servedDirs = mkOption {
156+ type = types.listOf types.attrs;
157+ default = [];
158+ example = [
159+ { urlPath = "/nix";
160+ dir = "/home/eelco/Dev/nix-homepage";
161+ }
162+ ];
163+ description = ''
164+ This option provides a simple way to serve static directories.
165+ '';
166+ };
167+
168+ servedFiles = mkOption {
169+ type = types.listOf types.attrs;
170+ default = [];
171+ example = [
172+ { urlPath = "/foo/bar.png";
173+ file = "/home/eelco/some-file.png";
174+ }
175+ ];
176+ description = ''
177+ This option provides a simple way to serve individual, static files.
178+ '';
179+ };
180+
181+ extraConfig = mkOption {
182+ type = types.lines;
183+ default = "";
184+ example = ''
185+ <Directory /home>
186+ Options FollowSymlinks
187+ AllowOverride All
188+ </Directory>
189+ '';
190+ description = ''
191+ These lines go to httpd.conf verbatim. They will go after
192+ directories and directory aliases defined by default.
193+ '';
194+ };
195+
196+ enableUserDir = mkOption {
197+ type = types.bool;
198+ default = false;
199+ description = ''
200+ Whether to enable serving <filename>~/public_html</filename> as
201+ <literal>/~<replaceable>username</replaceable></literal>.
202+ '';
203+ };
204+
205+ globalRedirect = mkOption {
206+ type = types.nullOr types.str;
207+ default = null;
208+ example = http://newserver.example.org/;
209+ description = ''
210+ If set, all requests for this host are redirected permanently to
211+ the given URL.
212+ '';
213+ };
214+
215+ logFormat = mkOption {
216+ type = types.str;
217+ default = "common";
218+ example = "combined";
219+ description = ''
220+ Log format for Apache's log files. Possible values are: combined, common, referer, agent.
221+ '';
222+ };
223+
224+ robotsEntries = mkOption {
225+ type = types.lines;
226+ default = "";
227+ example = "Disallow: /foo/";
228+ description = ''
229+ Specification of pages to be ignored by web crawlers. See <link
230+ xlink:href='http://www.robotstxt.org/'/> for details.
231+ '';
232+ };
11233
12− hostName = mkOption {
13− type = types.str;
14− default = "localhost";
15− description = "Canonical hostname for the server.";
16− };
17−
18− serverAliases = mkOption {
19− type = types.listOf types.str;
20− default = [];
21− example = ["www.example.org" "www.example.org:8080" "example.org"];
22− description = ''
23− Additional names of virtual hosts served by this virtual host configuration.
24− '';
25− };
26−
27− listen = mkOption {
28− type = types.listOf (types.submodule (
29− {
30− options = {
31− port = mkOption {
32− type = types.int;
33− description = "port to listen on";
34− };
35− ip = mkOption {
36− type = types.str;
37− default = "*";
38− description = "Ip to listen on. 0.0.0.0 for ipv4 only, * for all.";
39− };
40− };
41− } ));
42− description = ''
43− List of { /* ip: "*"; */ port = 80;} to listen on
44− '';
45−
46− default = [];
47− };
48−
49− enableSSL = mkOption {
50− type = types.bool;
51− default = false;
52− description = "Whether to enable SSL (https) support.";
53234 };
54−
55− # Note: sslServerCert and sslServerKey can be left empty, but this
56− # only makes sense for virtual hosts (they will inherit from the
57− # main server).
58−
59− sslServerCert = mkOption {
60− type = types.nullOr types.path;
61− default = null;
62− example = "/var/host.cert";
63− description = "Path to server SSL certificate.";
64− };
65−
66− sslServerKey = mkOption {
67− type = types.path;
68− example = "/var/host.key";
69− description = "Path to server SSL certificate key.";
70− };
71−
72− sslServerChain = mkOption {
73− type = types.nullOr types.path;
74− default = null;
75− example = "/var/ca.pem";
76− description = "Path to server SSL chain file.";
77− };
78−
79− adminAddr = mkOption ({
80− type = types.nullOr types.str;
81− example = "admin@example.org";
82− description = "E-mail address of the server administrator.";
83− } // (if forMainServer then {} else {default = null;}));
84−
85− documentRoot = mkOption {
86− type = types.nullOr types.path;
87− default = null;
88− example = "/data/webserver/docs";
89− description = ''
90− The path of Apache's document root directory. If left undefined,
91− an empty directory in the Nix store will be used as root.
92− '';
93− };
94−
95− servedDirs = mkOption {
96− type = types.listOf types.attrs;
97− default = [];
98− example = [
99− { urlPath = "/nix";
100− dir = "/home/eelco/Dev/nix-homepage";
101− }
102− ];
103− description = ''
104− This option provides a simple way to serve static directories.
105− '';
106− };
107−
108− servedFiles = mkOption {
109− type = types.listOf types.attrs;
110− default = [];
111− example = [
112− { urlPath = "/foo/bar.png";
113− file = "/home/eelco/some-file.png";
114− }
115− ];
116− description = ''
117− This option provides a simple way to serve individual, static files.
118− '';
119− };
120−
121− extraConfig = mkOption {
122− type = types.lines;
123− default = "";
124− example = ''
125− <Directory /home>
126− Options FollowSymlinks
127− AllowOverride All
128− </Directory>
129− '';
130− description = ''
131− These lines go to httpd.conf verbatim. They will go after
132− directories and directory aliases defined by default.
133− '';
134− };
135−
136− enableUserDir = mkOption {
137− type = types.bool;
138− default = false;
139− description = ''
140− Whether to enable serving <filename>~/public_html</filename> as
141− <literal>/~<replaceable>username</replaceable></literal>.
142− '';
143− };
144−
145− globalRedirect = mkOption {
146− type = types.nullOr types.str;
147− default = null;
148− example = http://newserver.example.org/;
149− description = ''
150− If set, all requests for this host are redirected permanently to
151− the given URL.
152− '';
153− };
154−
155− logFormat = mkOption {
156− type = types.str;
157− default = "common";
158− example = "combined";
159− description = ''
160− Log format for Apache's log files. Possible values are: combined, common, referer, agent.
161− '';
162− };
163−
164− robotsEntries = mkOption {
165− type = types.lines;
166− default = "";
167− example = "Disallow: /foo/";
168− description = ''
169− Specification of pages to be ignored by web crawlers. See <link
170− xlink:href='http://www.robotstxt.org/'/> for details.
171− '';
172− };
173−
174235}
nixos/tests/ec2.nix+1−1
@@ -113,7 +113,7 @@ in {
113113 services.httpd = {
114114 enable = true;
115115 adminAddr = "test@example.org";
116− documentRoot = "${pkgs.valgrind.doc}/share/doc/valgrind/html";
116+ virtualHosts.localhost.documentRoot = "${pkgs.valgrind.doc}/share/doc/valgrind/html";
117117 };
118118 networking.firewall.allowedTCPPorts = [ 80 ];
119119 }
nixos/tests/haproxy.nix+8−6
@@ -23,12 +23,14 @@ import ./make-test-python.nix ({ pkgs, ...}: {
2323 };
2424 services.httpd = {
2525 enable = true;
26− documentRoot = pkgs.writeTextDir "index.txt" "We are all good!";
27− adminAddr = "notme@yourhost.local";
28− listen = [{
29− ip = "::1";
30− port = 8000;
31− }];
26+ virtualHosts.localhost = {
27+ documentRoot = pkgs.writeTextDir "index.txt" "We are all good!";
28+ adminAddr = "notme@yourhost.local";
29+ listen = [{
30+ ip = "::1";
31+ port = 8000;
32+ }];
33+ };
3234 };
3335 };
3436 };
nixos/tests/hitch/default.nix+1−1
@@ -16,7 +16,7 @@ import ../make-test-python.nix ({ pkgs, ... }:
1616
1717 services.httpd = {
1818 enable = true;
19− documentRoot = ./example;
19+ virtualHosts.localhost.documentRoot = ./example;
2020 adminAddr = "noone@testing.nowhere";
2121 };
2222 };
nixos/tests/proxy.nix+8−7
@@ -1,4 +1,4 @@
1−import ./make-test.nix ({ pkgs, ...} :
1+import ./make-test.nix ({ pkgs, ...} :
22
33let
44
@@ -7,7 +7,7 @@ let
77
88 { services.httpd.enable = true;
99 services.httpd.adminAddr = "foo@example.org";
10− services.httpd.documentRoot = "${pkgs.valgrind.doc}/share/doc/valgrind/html";
10+ services.httpd.virtualHosts.localhost.documentRoot = "${pkgs.valgrind.doc}/share/doc/valgrind/html";
1111 networking.firewall.allowedTCPPorts = [ 80 ];
1212 };
1313
@@ -26,11 +26,11 @@ in
2626 { services.httpd.enable = true;
2727 services.httpd.adminAddr = "bar@example.org";
2828 services.httpd.extraModules = [ "proxy_balancer" "lbmethod_byrequests" ];
29−
30− services.httpd.extraConfig =
31− ''
32− ExtendedStatus on
33−
29+ services.httpd.extraConfig = ''
30+ ExtendedStatus on
31+ '';
32+ services.httpd.virtualHosts.localhost = {
33+ extraConfig = ''
3434 <Location /server-status>
3535 Require all granted
3636 SetHandler server-status
@@ -50,6 +50,7 @@ in
5050 # For testing; don't want to wait forever for dead backend servers.
5151 ProxyTimeout 5
5252 '';
53+ };
5354
5455 networking.firewall.allowedTCPPorts = [ 80 ];
5556 };
nixos/tests/upnp.nix+5−3
@@ -56,9 +56,11 @@ in
5656 networking.firewall.enable = false;
5757
5858 services.httpd.enable = true;
59− services.httpd.listen = [{ ip = "*"; port = 9000; }];
60− services.httpd.adminAddr = "foo@example.org";
61− services.httpd.documentRoot = "/tmp";
59+ services.httpd.virtualHosts.localhost = {
60+ listen = [{ ip = "*"; port = 9000; }];
61+ adminAddr = "foo@example.org";
62+ documentRoot = "/tmp";
63+ };
6264 };
6365
6466 client2 =