1{ config, lib, pkgs, ... }:
2
3with lib;
4
5let
6 cfg = config.services.nginx;
7 nginx = cfg.package;
8 configFile = pkgs.writeText "nginx.conf" ''
9 user ${cfg.user} ${cfg.group};
10 daemon off;
11
12 ${cfg.config}
13
14 ${optionalString (cfg.httpConfig != "") ''
15 http {
16 include ${cfg.package}/conf/mime.types;
17 ${cfg.httpConfig}
18 }
19 ''}
20 ${cfg.appendConfig}
21 '';
22in
23
24{
25 options = {
26 services.nginx = {
27 enable = mkOption {
28 default = false;
29 type = types.bool;
30 description = "
31 Enable the nginx Web Server.
32 ";
33 };
34
35 package = mkOption {
36 default = pkgs.nginx;
37 type = types.package;
38 description = "
39 Nginx package to use.
40 ";
41 };
42
43 config = mkOption {
44 default = "events {}";
45 description = "
46 Verbatim nginx.conf configuration.
47 ";
48 };
49
50 appendConfig = mkOption {
51 type = types.lines;
52 default = "";
53 description = ''
54 Configuration lines appended to the generated Nginx
55 configuration file. Commonly used by different modules
56 providing http snippets. <option>appendConfig</option>
57 can be specified more than once and it's value will be
58 concatenated (contrary to <option>config</option> which
59 can be set only once).
60 '';
61 };
62
63 httpConfig = mkOption {
64 type = types.lines;
65 default = "";
66 description = "Configuration lines to be appended inside of the http {} block.";
67 };
68
69 stateDir = mkOption {
70 default = "/var/spool/nginx";
71 description = "
72 Directory holding all state for nginx to run.
73 ";
74 };
75
76 user = mkOption {
77 type = types.str;
78 default = "nginx";
79 description = "User account under which nginx runs.";
80 };
81
82 group = mkOption {
83 type = types.str;
84 default = "nginx";
85 description = "Group account under which nginx runs.";
86 };
87
88 };
89
90 };
91
92 config = mkIf cfg.enable {
93 # TODO: test user supplied config file pases syntax test
94
95 systemd.services.nginx = {
96 description = "Nginx Web Server";
97 after = [ "network.target" ];
98 wantedBy = [ "multi-user.target" ];
99 path = [ nginx ];
100 preStart =
101 ''
102 mkdir -p ${cfg.stateDir}/logs
103 chmod 700 ${cfg.stateDir}
104 chown -R ${cfg.user}:${cfg.group} ${cfg.stateDir}
105 '';
106 serviceConfig = {
107 ExecStart = "${nginx}/bin/nginx -c ${configFile} -p ${cfg.stateDir}";
108 ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID";
109 Restart = "on-failure";
110 RestartSec = "10s";
111 StartLimitInterval = "1min";
112 };
113 };
114
115 users.extraUsers = optionalAttrs (cfg.user == "nginx") (singleton
116 { name = "nginx";
117 group = cfg.group;
118 uid = config.ids.uids.nginx;
119 });
120
121 users.extraGroups = optionalAttrs (cfg.group == "nginx") (singleton
122 { name = "nginx";
123 gid = config.ids.gids.nginx;
124 });
125 };
126}