@@ -4,31 +4,222 @@ with lib;
44
55let
66 cfg = config.services.nginx;
7− nginx = cfg.package;
7+ virtualHosts = mapAttrs (vhostName: vhostConfig:
8+ vhostConfig // (optionalAttrs vhostConfig.enableACME {
9+ sslCertificate = "/var/lib/acme/${vhostName}/fullchain.pem";
10+ sslCertificateKey = "/var/lib/acme/${vhostName}/key.pem";
11+ })
12+ ) cfg.virtualHosts;
13+
814 configFile = pkgs.writeText "nginx.conf" ''
915 user ${cfg.user} ${cfg.group};
16+ error_log stderr;
1017 daemon off;
1118
1219 ${cfg.config}
1320
21+ ${optionalString (cfg.httpConfig == "") ''
22+ http {
23+ include ${cfg.package}/conf/mime.types;
24+ include ${cfg.package}/conf/fastcgi.conf;
25+
26+ ${optionalString (cfg.recommendedOptimisation) ''
27+ # optimisation
28+ sendfile on;
29+ tcp_nopush on;
30+ tcp_nodelay on;
31+ keepalive_timeout 65;
32+ types_hash_max_size 2048;
33+ ''}
34+
35+ ssl_protocols ${cfg.sslProtocols};
36+ ssl_ciphers ${cfg.sslCiphers};
37+ ${optionalString (cfg.sslDhparam != null) "ssl_dhparam ${cfg.sslDhparam};"}
38+
39+ ${optionalString (cfg.recommendedTlsSettings) ''
40+ ssl_session_cache shared:SSL:42m;
41+ ssl_session_timeout 23m;
42+ ssl_ecdh_curve secp384r1;
43+ ssl_prefer_server_ciphers on;
44+ ssl_stapling on;
45+ ssl_stapling_verify on;
46+ ''}
47+
48+ ${optionalString (cfg.recommendedGzipSettings) ''
49+ gzip on;
50+ gzip_disable "msie6";
51+ gzip_proxied any;
52+ gzip_comp_level 9;
53+ gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
54+ ''}
55+
56+ ${optionalString (cfg.recommendedProxySettings) ''
57+ proxy_set_header Host $host;
58+ proxy_set_header X-Real-IP $remote_addr;
59+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
60+ proxy_set_header X-Forwarded-Proto $scheme;
61+ proxy_set_header X-Forwarded-Host $host;
62+ proxy_set_header X-Forwarded-Server $host;
63+ proxy_set_header Accept-Encoding "";
64+
65+ proxy_redirect off;
66+ proxy_connect_timeout 90;
67+ proxy_send_timeout 90;
68+ proxy_read_timeout 90;
69+ proxy_http_version 1.0;
70+ ''}
71+
72+ client_max_body_size ${cfg.clientMaxBodySize};
73+
74+ server_tokens ${if cfg.serverTokens then "on" else "off"};
75+
76+ ${vhosts}
77+
78+ ${optionalString cfg.statusPage ''
79+ server {
80+ listen 80;
81+ listen [::]:80;
82+
83+ server_name localhost;
84+
85+ location /nginx_status {
86+ stub_status on;
87+ access_log off;
88+ allow 127.0.0.1;
89+ allow ::1;
90+ deny all;
91+ }
92+ }
93+ ''}
94+
95+ ${cfg.appendHttpConfig}
96+ }''}
97+
1498 ${optionalString (cfg.httpConfig != "") ''
1599 http {
16100 include ${cfg.package}/conf/mime.types;
101+ include ${cfg.package}/conf/fastcgi.conf;
17102 ${cfg.httpConfig}
18− }
19− ''}
103+ }''}
104+
20105 ${cfg.appendConfig}
21106 '';
107+
108+ vhosts = concatStringsSep "\n" (mapAttrsToList (serverName: vhost:
109+ let
110+ ssl = vhost.enableSSL || vhost.forceSSL;
111+ port = if vhost.port != null then vhost.port else (if ssl then 443 else 80);
112+ listenString = toString port + optionalString ssl " ssl http2"
113+ + optionalString vhost.default " default";
114+ acmeLocation = optionalString vhost.enableACME ''
115+ location /.well-known/acme-challenge {
116+ try_files $uri @acme-fallback;
117+ root ${vhost.acmeRoot};
118+ auth_basic off;
119+ }
120+ location @acme-fallback {
121+ auth_basic off;
122+ proxy_pass http://${vhost.acmeFallbackHost};
123+ }
124+ '';
125+ in ''
126+ ${optionalString vhost.forceSSL ''
127+ server {
128+ listen 80 ${optionalString vhost.default "default"};
129+ listen [::]:80 ${optionalString vhost.default "default"};
130+
131+ server_name ${serverName} ${concatStringsSep " " vhost.serverAliases};
132+ ${acmeLocation}
133+ location / {
134+ return 301 https://$host${optionalString (port != 443) ":${port}"}$request_uri;
135+ }
136+ }
137+ ''}
138+
139+ server {
140+ listen ${listenString};
141+ listen [::]:${listenString};
142+
143+ server_name ${serverName} ${concatStringsSep " " vhost.serverAliases};
144+ ${acmeLocation}
145+ ${optionalString (vhost.root != null) "root ${vhost.root};"}
146+ ${optionalString (vhost.globalRedirect != null) ''
147+ return 301 http${optionalString ssl "s"}://${vhost.globalRedirect}$request_uri;
148+ ''}
149+ ${optionalString ssl ''
150+ ssl_certificate ${vhost.sslCertificate};
151+ ssl_certificate_key ${vhost.sslCertificateKey};
152+ ''}
153+
154+ ${optionalString (vhost.basicAuth != {}) (mkBasicAuth serverName vhost.basicAuth)}
155+
156+ ${mkLocations vhost.locations}
157+
158+ ${vhost.extraConfig}
159+ }
160+ ''
161+ ) virtualHosts);
162+ mkLocations = locations: concatStringsSep "\n" (mapAttrsToList (location: config: ''
163+ location ${location} {
164+ ${optionalString (config.proxyPass != null) "proxy_pass ${config.proxyPass};"}
165+ ${optionalString (config.root != null) "root ${config.root};"}
166+ ${config.extraConfig}
167+ }
168+ '') locations);
169+ mkBasicAuth = serverName: authDef: let
170+ htpasswdFile = pkgs.writeText "${serverName}.htpasswd" (
171+ concatStringsSep "\n" (mapAttrsToList (user: password: ''
172+ ${user}:{PLAIN}${password}
173+ '') authDef)
174+ );
175+ in ''
176+ auth_basic secured;
177+ auth_basic_user_file ${htpasswdFile};
178+ '';
22179in
23180
24181{
25182 options = {
26183 services.nginx = {
27− enable = mkOption {
184+ enable = mkEnableOption "Nginx Web Server";
185+
186+ statusPage = mkOption {
187+ default = false;
188+ type = types.bool;
189+ description = "
190+ Enable status page reachable from localhost on http://127.0.0.1/nginx_status.
191+ ";
192+ };
193+
194+ recommendedTlsSettings = mkOption {
195+ default = false;
196+ type = types.bool;
197+ description = "
198+ Enable recommended TLS settings.
199+ ";
200+ };
201+
202+ recommendedOptimisation = mkOption {
203+ default = false;
204+ type = types.bool;
205+ description = "
206+ Enable recommended optimisation settings.
207+ ";
208+ };
209+
210+ recommendedGzipSettings = mkOption {
211+ default = false;
212+ type = types.bool;
213+ description = "
214+ Enable recommended gzip settings.
215+ ";
216+ };
217+
218+ recommendedProxySettings = mkOption {
28219 default = false;
29220 type = types.bool;
30221 description = "
31− Enable the nginx Web Server.
222+ Enable recommended proxy settings.
32223 ";
33224 };
34225
@@ -64,7 +255,22 @@ in
64255 httpConfig = mkOption {
65256 type = types.lines;
66257 default = "";
67− description = "Configuration lines to be appended inside of the http {} block.";
258+ description = "
259+ Configuration lines to be set inside the http block.
260+ This is mutually exclusive with the structured configuration
261+ via virtualHosts and the recommendedXyzSettings configuration
262+ options. See appendHttpConfig for appending to the generated http block.
263+ ";
264+ };
265+
266+ appendHttpConfig = mkOption {
267+ type = types.lines;
268+ default = "";
269+ description = "
270+ Configuration lines to be appended to the generated http block.
271+ This is mutually exclusive with using httpConfig for specifying the whole
272+ http block verbatim.
273+ ";
68274 };
69275
70276 stateDir = mkOption {
@@ -86,8 +292,59 @@ in
86292 description = "Group account under which nginx runs.";
87293 };
88294
89− };
295+ serverTokens = mkOption {
296+ type = types.bool;
297+ default = false;
298+ description = "Show nginx version in headers and error pages.";
299+ };
300+
301+ clientMaxBodySize = mkOption {
302+ type = types.string;
303+ default = "10m";
304+ description = "Set nginx global client_max_body_size.";
305+ };
306+
307+ sslCiphers = mkOption {
308+ type = types.str;
309+ default = "EECDH+aRSA+AESGCM:EDH+aRSA:EECDH+aRSA:+AES256:+AES128:+SHA1:!CAMELLIA:!SEED:!3DES:!DES:!RC4:!eNULL";
310+ description = "Ciphers to choose from when negotiating tls handshakes.";
311+ };
312+
313+ sslProtocols = mkOption {
314+ type = types.str;
315+ default = "TLSv1.2";
316+ example = "TLSv1 TLSv1.1 TLSv1.2";
317+ description = "Allowed TLS protocol versions.";
318+ };
319+
320+ sslDhparam = mkOption {
321+ type = types.nullOr types.path;
322+ default = null;
323+ example = "/path/to/dhparams.pem";
324+ description = "Path to DH parameters file.";
325+ };
90326
327+ virtualHosts = mkOption {
328+ type = types.attrsOf (types.submodule (import ./vhost-options.nix {
329+ inherit lib;
330+ }));
331+ default = {
332+ localhost = {};
333+ };
334+ example = literalExample ''
335+ {
336+ "hydra.example.com" = {
337+ forceSSL = true;
338+ enableACME = true;
339+ locations."/" = {
340+ proxyPass = "http://localhost:3000";
341+ };
342+ };
343+ };
344+ '';
345+ description = "Declarative vhost config";
346+ };
347+ };
91348 };
92349
93350 config = mkIf cfg.enable {
@@ -97,7 +354,6 @@ in
97354 description = "Nginx Web Server";
98355 after = [ "network.target" ];
99356 wantedBy = [ "multi-user.target" ];
100− path = [ nginx ];
101357 preStart =
102358 ''
103359 mkdir -p ${cfg.stateDir}/logs
@@ -105,14 +361,23 @@ in
105361 chown -R ${cfg.user}:${cfg.group} ${cfg.stateDir}
106362 '';
107363 serviceConfig = {
108− ExecStart = "${nginx}/bin/nginx -c ${configFile} -p ${cfg.stateDir}";
364+ ExecStart = "${cfg.package}/bin/nginx -c ${configFile} -p ${cfg.stateDir}";
109365 ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID";
110− Restart = "on-failure";
366+ Restart = "always";
111367 RestartSec = "10s";
112368 StartLimitInterval = "1min";
113369 };
114370 };
115371
372+ security.acme.certs = filterAttrs (n: v: v != {}) (
373+ mapAttrs (vhostName: vhostConfig:
374+ optionalAttrs vhostConfig.enableACME {
375+ webroot = vhostConfig.acmeRoot;
376+ extraDomains = genAttrs vhostConfig.serverAliases (alias: null);
377+ }
378+ ) virtualHosts
379+ );
380+
116381 users.extraUsers = optionalAttrs (cfg.user == "nginx") (singleton
117382 { name = "nginx";
118383 group = cfg.group;