git.iko.soy/typeable/nixpkgs
on master help sign in
Merge pull request #15862 from mayflower/nginx-module

Declarative nginx module with ACME support

commit34237beca6206475dec1f1c68edf227401793382 authorRok Garbas <rok@garbas.si> dateMon 1 Aug 2016, 13:10 (10 years ago) parentc91d07ba193fec
3 files changed+455−10
nixos/modules/services/web-servers/nginx/default.nix+275−10 nixos/modules/services/web-servers/nginx/location-options.nix+40 nixos/modules/services/web-servers/nginx/vhost-options.nix+140
nixos/modules/services/web-servers/nginx/default.nix+275−10
@@ -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;
nixos/modules/services/web-servers/nginx/location-options.nixnew file+40
@@ -0,0 +1,40 @@
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+{ lib }:
7+
8+with lib;
9+
10+{
11+ options = {
12+ proxyPass = mkOption {
13+ type = types.nullOr types.str;
14+ default = null;
15+ example = "http://www.example.org/";
16+ description = ''
17+ Adds proxy_pass directive and sets default proxy headers Host, X-Real-Ip
18+ and X-Forwarded-For.
19+ '';
20+ };
21+
22+ root = mkOption {
23+ type = types.nullOr types.path;
24+ default = null;
25+ example = /your/root/directory;
26+ description = ''
27+ Root directory for requests.
28+ '';
29+ };
30+
31+ extraConfig = mkOption {
32+ type = types.lines;
33+ default = "";
34+ description = ''
35+ These lines go to the end of the location verbatim.
36+ '';
37+ };
38+ };
39+}
40+
nixos/modules/services/web-servers/nginx/vhost-options.nixnew file+140
@@ -0,0 +1,140 @@
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+{ lib }:
7+
8+with lib;
9+{
10+ options = {
11+ serverAliases = mkOption {
12+ type = types.listOf types.str;
13+ default = [];
14+ example = ["www.example.org" "example.org"];
15+ description = ''
16+ Additional names of virtual hosts served by this virtual host configuration.
17+ '';
18+ };
19+
20+ port = mkOption {
21+ type = types.nullOr types.int;
22+ default = null;
23+ description = ''
24+ Port for the server. Defaults to 80 for http
25+ and 443 for https (i.e. when enableSSL is set).
26+ '';
27+ };
28+
29+ enableACME = mkOption {
30+ type = types.bool;
31+ default = false;
32+ description = "Whether to ask Let's Encrypt to sign a certificate for this vhost.";
33+ };
34+
35+ acmeRoot = mkOption {
36+ type = types.str;
37+ default = "/var/lib/acme/acme-challenge";
38+ description = "Directory to store certificates and keys managed by the ACME service.";
39+ };
40+
41+ acmeFallbackHost = mkOption {
42+ type = types.str;
43+ default = "0.0.0.0";
44+ description = ''
45+ Host which to proxy requests to if acme challenge is not found. Useful
46+ if you want multiple hosts to be able to verify the same domain name.
47+ '';
48+ };
49+
50+ enableSSL = mkOption {
51+ type = types.bool;
52+ default = false;
53+ description = "Whether to enable SSL (https) support.";
54+ };
55+
56+ forceSSL = mkOption {
57+ type = types.bool;
58+ default = false;
59+ description = "Whether to always redirect to https.";
60+ };
61+
62+ sslCertificate = mkOption {
63+ type = types.path;
64+ example = "/var/host.cert";
65+ description = "Path to server SSL certificate.";
66+ };
67+
68+ sslCertificateKey = mkOption {
69+ type = types.path;
70+ example = "/var/host.key";
71+ description = "Path to server SSL certificate key.";
72+ };
73+
74+ root = mkOption {
75+ type = types.nullOr types.path;
76+ default = null;
77+ example = "/data/webserver/docs";
78+ description = ''
79+ The path of the web root directory.
80+ '';
81+ };
82+
83+ default = mkOption {
84+ type = types.bool;
85+ default = false;
86+ description = ''
87+ Makes this vhost the default.
88+ '';
89+ };
90+
91+ extraConfig = mkOption {
92+ type = types.lines;
93+ default = "";
94+ description = ''
95+ These lines go to the end of the vhost verbatim.
96+ '';
97+ };
98+
99+ globalRedirect = mkOption {
100+ type = types.nullOr types.str;
101+ default = null;
102+ example = http://newserver.example.org/;
103+ description = ''
104+ If set, all requests for this host are redirected permanently to
105+ the given URL.
106+ '';
107+ };
108+
109+ basicAuth = mkOption {
110+ type = types.attrsOf types.str;
111+ default = {};
112+ example = literalExample ''
113+ {
114+ user = "password";
115+ };
116+ '';
117+ description = ''
118+ Basic Auth protection for a vhost.
119+
120+ WARNING: This is implemented to store the password in plain text in the
121+ nix store.
122+ '';
123+ };
124+
125+ locations = mkOption {
126+ type = types.attrsOf (types.submodule (import ./location-options.nix {
127+ inherit lib;
128+ }));
129+ default = {};
130+ example = literalExample ''
131+ {
132+ "/" = {
133+ proxyPass = "http://localhost:3000";
134+ };
135+ };
136+ '';
137+ description = "Declarative location config";
138+ };
139+ };
140+}