1{ config, lib, pkgs, ... }: 2 3with lib; 4 5let 6 7 cfg = config.services.httpd; 8 9 certs = config.security.acme.certs; 10 11 runtimeDir = "/run/httpd"; 12 13 pkg = cfg.package.out; 14 15 apachectl = pkgs.runCommand "apachectl" { meta.priority = -1; } '' 16 mkdir -p $out/bin 17 cp ${pkg}/bin/apachectl $out/bin/apachectl 18 sed -i $out/bin/apachectl -e 's|$HTTPD -t|$HTTPD -t -f /etc/httpd/httpd.conf|' 19 ''; 20 21 php = cfg.phpPackage.override { apacheHttpd = pkg; }; 22 23 phpModuleName = let 24 majorVersion = lib.versions.major (lib.getVersion php); 25 in (if majorVersion == "8" then "php" else "php${majorVersion}"); 26 27 mod_perl = pkgs.apacheHttpdPackages.mod_perl.override { apacheHttpd = pkg; }; 28 29 vhosts = attrValues cfg.virtualHosts; 30 31 # certName is used later on to determine systemd service names. 32 acmeEnabledVhosts = map (hostOpts: hostOpts // { 33 certName = if hostOpts.useACMEHost != null then hostOpts.useACMEHost else hostOpts.hostName; 34 }) (filter (hostOpts: hostOpts.enableACME || hostOpts.useACMEHost != null) vhosts); 35 36 dependentCertNames = unique (map (hostOpts: hostOpts.certName) acmeEnabledVhosts); 37 38 mkListenInfo = hostOpts: 39 if hostOpts.listen != [] then 40 hostOpts.listen 41 else 42 optionals (hostOpts.onlySSL || hostOpts.addSSL || hostOpts.forceSSL) (map (addr: { ip = addr; port = 443; ssl = true; }) hostOpts.listenAddresses) ++ 43 optionals (!hostOpts.onlySSL) (map (addr: { ip = addr; port = 80; ssl = false; }) hostOpts.listenAddresses) 44 ; 45 46 listenInfo = unique (concatMap mkListenInfo vhosts); 47 48 enableHttp2 = any (vhost: vhost.http2) vhosts; 49 enableSSL = any (listen: listen.ssl) listenInfo; 50 enableUserDir = any (vhost: vhost.enableUserDir) vhosts; 51 52 # NOTE: generally speaking order of modules is very important 53 modules = 54 [ # required apache modules our httpd service cannot run without 55 "authn_core" "authz_core" 56 "log_config" 57 "mime" "autoindex" "negotiation" "dir" 58 "alias" "rewrite" 59 "unixd" "slotmem_shm" "socache_shmcb" 60 "mpm_${cfg.mpm}" 61 ] 62 ++ (if cfg.mpm == "prefork" then [ "cgi" ] else [ "cgid" ]) 63 ++ optional enableHttp2 "http2" 64 ++ optional enableSSL "ssl" 65 ++ optional enableUserDir "userdir" 66 ++ optional cfg.enableMellon { name = "auth_mellon"; path = "${pkgs.apacheHttpdPackages.mod_auth_mellon}/modules/mod_auth_mellon.so"; } 67 ++ optional cfg.enablePHP { name = phpModuleName; path = "${php}/modules/lib${phpModuleName}.so"; } 68 ++ optional cfg.enablePerl { name = "perl"; path = "${mod_perl}/modules/mod_perl.so"; } 69 ++ cfg.extraModules; 70 71 loggingConf = (if cfg.logFormat != "none" then '' 72 ErrorLog ${cfg.logDir}/error.log 73 74 LogLevel notice 75 76 LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined 77 LogFormat "%h %l %u %t \"%r\" %>s %b" common 78 LogFormat "%{Referer}i -> %U" referer 79 LogFormat "%{User-agent}i" agent 80 81 CustomLog ${cfg.logDir}/access.log ${cfg.logFormat} 82 '' else '' 83 ErrorLog /dev/null 84 ''); 85 86 87 browserHacks = '' 88 <IfModule mod_setenvif.c> 89 BrowserMatch "Mozilla/2" nokeepalive 90 BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 91 BrowserMatch "RealPlayer 4\.0" force-response-1.0 92 BrowserMatch "Java/1\.0" force-response-1.0 93 BrowserMatch "JDK/1\.0" force-response-1.0 94 BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully 95 BrowserMatch "^WebDrive" redirect-carefully 96 BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully 97 BrowserMatch "^gnome-vfs" redirect-carefully 98 </IfModule> 99 ''; 100 101 102 sslConf = '' 103 <IfModule mod_ssl.c> 104 SSLSessionCache shmcb:${runtimeDir}/ssl_scache(512000) 105 106 Mutex posixsem 107 108 SSLRandomSeed startup builtin 109 SSLRandomSeed connect builtin 110 111 SSLProtocol ${cfg.sslProtocols} 112 SSLCipherSuite ${cfg.sslCiphers} 113 SSLHonorCipherOrder on 114 </IfModule> 115 ''; 116 117 118 mimeConf = '' 119 TypesConfig ${pkg}/conf/mime.types 120 121 AddType application/x-x509-ca-cert .crt 122 AddType application/x-pkcs7-crl .crl 123 AddType application/x-httpd-php .php .phtml 124 125 <IfModule mod_mime_magic.c> 126 MIMEMagicFile ${pkg}/conf/magic 127 </IfModule> 128 ''; 129 130 luaSetPaths = let 131 # support both lua and lua.withPackages derivations 132 luaversion = cfg.package.lua5.lua.luaversion or cfg.package.lua5.luaversion; 133 in 134 '' 135 <IfModule mod_lua.c> 136 LuaPackageCPath ${cfg.package.lua5}/lib/lua/${luaversion}/?.so 137 LuaPackagePath ${cfg.package.lua5}/share/lua/${luaversion}/?.lua 138 </IfModule> 139 ''; 140 141 mkVHostConf = hostOpts: 142 let 143 adminAddr = if hostOpts.adminAddr != null then hostOpts.adminAddr else cfg.adminAddr; 144 listen = filter (listen: !listen.ssl) (mkListenInfo hostOpts); 145 listenSSL = filter (listen: listen.ssl) (mkListenInfo hostOpts); 146 147 useACME = hostOpts.enableACME || hostOpts.useACMEHost != null; 148 sslCertDir = 149 if hostOpts.enableACME then certs.${hostOpts.hostName}.directory 150 else if hostOpts.useACMEHost != null then certs.${hostOpts.useACMEHost}.directory 151 else abort "This case should never happen."; 152 153 sslServerCert = if useACME then "${sslCertDir}/fullchain.pem" else hostOpts.sslServerCert; 154 sslServerKey = if useACME then "${sslCertDir}/key.pem" else hostOpts.sslServerKey; 155 sslServerChain = if useACME then "${sslCertDir}/chain.pem" else hostOpts.sslServerChain; 156 157 acmeChallenge = optionalString useACME '' 158 Alias /.well-known/acme-challenge/ "${hostOpts.acmeRoot}/.well-known/acme-challenge/" 159 <Directory "${hostOpts.acmeRoot}"> 160 AllowOverride None 161 Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec 162 Require method GET POST OPTIONS 163 Require all granted 164 </Directory> 165 ''; 166 in 167 optionalString (listen != []) '' 168 <VirtualHost ${concatMapStringsSep " " (listen: "${listen.ip}:${toString listen.port}") listen}> 169 ServerName ${hostOpts.hostName} 170 ${concatMapStrings (alias: "ServerAlias ${alias}\n") hostOpts.serverAliases} 171 ServerAdmin ${adminAddr} 172 <IfModule mod_ssl.c> 173 SSLEngine off 174 </IfModule> 175 ${acmeChallenge} 176 ${if hostOpts.forceSSL then '' 177 <IfModule mod_rewrite.c> 178 RewriteEngine on 179 RewriteCond %{REQUEST_URI} !^/.well-known/acme-challenge [NC] 180 RewriteCond %{HTTPS} off 181 RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} 182 </IfModule> 183 '' else mkVHostCommonConf hostOpts} 184 </VirtualHost> 185 '' + 186 optionalString (listenSSL != []) '' 187 <VirtualHost ${concatMapStringsSep " " (listen: "${listen.ip}:${toString listen.port}") listenSSL}> 188 ServerName ${hostOpts.hostName} 189 ${concatMapStrings (alias: "ServerAlias ${alias}\n") hostOpts.serverAliases} 190 ServerAdmin ${adminAddr} 191 SSLEngine on 192 SSLCertificateFile ${sslServerCert} 193 SSLCertificateKeyFile ${sslServerKey} 194 ${optionalString (sslServerChain != null) "SSLCertificateChainFile ${sslServerChain}"} 195 ${optionalString hostOpts.http2 "Protocols h2 h2c http/1.1"} 196 ${acmeChallenge} 197 ${mkVHostCommonConf hostOpts} 198 </VirtualHost> 199 '' 200 ; 201 202 mkVHostCommonConf = hostOpts: 203 let 204 documentRoot = if hostOpts.documentRoot != null 205 then hostOpts.documentRoot 206 else pkgs.emptyDirectory 207 ; 208 209 mkLocations = locations: concatStringsSep "\n" (map (config: '' 210 <Location ${config.location}> 211 ${optionalString (config.proxyPass != null) '' 212 <IfModule mod_proxy.c> 213 ProxyPass ${config.proxyPass} 214 ProxyPassReverse ${config.proxyPass} 215 </IfModule> 216 ''} 217 ${optionalString (config.index != null) '' 218 <IfModule mod_dir.c> 219 DirectoryIndex ${config.index} 220 </IfModule> 221 ''} 222 ${optionalString (config.alias != null) '' 223 <IfModule mod_alias.c> 224 Alias "${config.alias}" 225 </IfModule> 226 ''} 227 ${config.extraConfig} 228 </Location> 229 '') (sortProperties (mapAttrsToList (k: v: v // { location = k; }) locations))); 230 in 231 '' 232 ${optionalString cfg.logPerVirtualHost '' 233 ErrorLog ${cfg.logDir}/error-${hostOpts.hostName}.log 234 CustomLog ${cfg.logDir}/access-${hostOpts.hostName}.log ${hostOpts.logFormat} 235 ''} 236 237 ${optionalString (hostOpts.robotsEntries != "") '' 238 Alias /robots.txt ${pkgs.writeText "robots.txt" hostOpts.robotsEntries} 239 ''} 240 241 DocumentRoot "${documentRoot}" 242 243 <Directory "${documentRoot}"> 244 Options Indexes FollowSymLinks 245 AllowOverride None 246 Require all granted 247 </Directory> 248 249 ${optionalString hostOpts.enableUserDir '' 250 UserDir public_html 251 UserDir disabled root 252 <Directory "/home/*/public_html"> 253 AllowOverride FileInfo AuthConfig Limit Indexes 254 Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec 255 <Limit GET POST OPTIONS> 256 Require all granted 257 </Limit> 258 <LimitExcept GET POST OPTIONS> 259 Require all denied 260 </LimitExcept> 261 </Directory> 262 ''} 263 264 ${optionalString (hostOpts.globalRedirect != null && hostOpts.globalRedirect != "") '' 265 RedirectPermanent / ${hostOpts.globalRedirect} 266 ''} 267 268 ${ 269 let makeDirConf = elem: '' 270 Alias ${elem.urlPath} ${elem.dir}/ 271 <Directory ${elem.dir}> 272 Options +Indexes 273 Require all granted 274 AllowOverride All 275 </Directory> 276 ''; 277 in concatMapStrings makeDirConf hostOpts.servedDirs 278 } 279 280 ${mkLocations hostOpts.locations} 281 ${hostOpts.extraConfig} 282 '' 283 ; 284 285 286 confFile = pkgs.writeText "httpd.conf" '' 287 288 ServerRoot ${pkg} 289 ServerName ${config.networking.hostName} 290 DefaultRuntimeDir ${runtimeDir}/runtime 291 292 PidFile ${runtimeDir}/httpd.pid 293 294 ${optionalString (cfg.mpm != "prefork") '' 295 # mod_cgid requires this. 296 ScriptSock ${runtimeDir}/cgisock 297 ''} 298 299 <IfModule prefork.c> 300 MaxClients ${toString cfg.maxClients} 301 MaxRequestsPerChild ${toString cfg.maxRequestsPerChild} 302 </IfModule> 303 304 ${let 305 toStr = listen: "Listen ${listen.ip}:${toString listen.port} ${if listen.ssl then "https" else "http"}"; 306 uniqueListen = uniqList {inputList = map toStr listenInfo;}; 307 in concatStringsSep "\n" uniqueListen 308 } 309 310 User ${cfg.user} 311 Group ${cfg.group} 312 313 ${let 314 mkModule = module: 315 if isString module then { name = module; path = "${pkg}/modules/mod_${module}.so"; } 316 else if isAttrs module then { inherit (module) name path; } 317 else throw "Expecting either a string or attribute set including a name and path."; 318 in 319 concatMapStringsSep "\n" (module: "LoadModule ${module.name}_module ${module.path}") (unique (map mkModule modules)) 320 } 321 322 AddHandler type-map var 323 324 <Files ~ "^\.ht"> 325 Require all denied 326 </Files> 327 328 ${mimeConf} 329 ${loggingConf} 330 ${browserHacks} 331 332 Include ${pkg}/conf/extra/httpd-default.conf 333 Include ${pkg}/conf/extra/httpd-autoindex.conf 334 Include ${pkg}/conf/extra/httpd-multilang-errordoc.conf 335 Include ${pkg}/conf/extra/httpd-languages.conf 336 337 TraceEnable off 338 339 ${sslConf} 340 341 ${optionalString cfg.package.luaSupport luaSetPaths} 342 343 # Fascist default - deny access to everything. 344 <Directory /> 345 Options FollowSymLinks 346 AllowOverride None 347 Require all denied 348 </Directory> 349 350 # But do allow access to files in the store so that we don't have 351 # to generate <Directory> clauses for every generated file that we 352 # want to serve. 353 <Directory /nix/store> 354 Require all granted 355 </Directory> 356 357 ${cfg.extraConfig} 358 359 ${concatMapStringsSep "\n" mkVHostConf vhosts} 360 ''; 361 362 # Generate the PHP configuration file. Should probably be factored 363 # out into a separate module. 364 phpIni = pkgs.runCommand "php.ini" 365 { options = cfg.phpOptions; 366 preferLocalBuild = true; 367 } 368 '' 369 cat ${php}/etc/php.ini > $out 370 cat ${php.phpIni} > $out 371 echo "$options" >> $out 372 ''; 373in 374 375 376{ 377 378 imports = [ 379 (mkRemovedOptionModule [ "services" "httpd" "extraSubservices" ] "Most existing subservices have been ported to the NixOS module system. Please update your configuration accordingly.") 380 (mkRemovedOptionModule [ "services" "httpd" "stateDir" ] "The httpd module now uses /run/httpd as a runtime directory.") 381 (mkRenamedOptionModule [ "services" "httpd" "multiProcessingModule" ] [ "services" "httpd" "mpm" ]) 382 383 # virtualHosts options 384 (mkRemovedOptionModule [ "services" "httpd" "documentRoot" ] "Please define a virtual host using `services.httpd.virtualHosts`.") 385 (mkRemovedOptionModule [ "services" "httpd" "enableSSL" ] "Please define a virtual host using `services.httpd.virtualHosts`.") 386 (mkRemovedOptionModule [ "services" "httpd" "enableUserDir" ] "Please define a virtual host using `services.httpd.virtualHosts`.") 387 (mkRemovedOptionModule [ "services" "httpd" "globalRedirect" ] "Please define a virtual host using `services.httpd.virtualHosts`.") 388 (mkRemovedOptionModule [ "services" "httpd" "hostName" ] "Please define a virtual host using `services.httpd.virtualHosts`.") 389 (mkRemovedOptionModule [ "services" "httpd" "listen" ] "Please define a virtual host using `services.httpd.virtualHosts`.") 390 (mkRemovedOptionModule [ "services" "httpd" "robotsEntries" ] "Please define a virtual host using `services.httpd.virtualHosts`.") 391 (mkRemovedOptionModule [ "services" "httpd" "servedDirs" ] "Please define a virtual host using `services.httpd.virtualHosts`.") 392 (mkRemovedOptionModule [ "services" "httpd" "servedFiles" ] "Please define a virtual host using `services.httpd.virtualHosts`.") 393 (mkRemovedOptionModule [ "services" "httpd" "serverAliases" ] "Please define a virtual host using `services.httpd.virtualHosts`.") 394 (mkRemovedOptionModule [ "services" "httpd" "sslServerCert" ] "Please define a virtual host using `services.httpd.virtualHosts`.") 395 (mkRemovedOptionModule [ "services" "httpd" "sslServerChain" ] "Please define a virtual host using `services.httpd.virtualHosts`.") 396 (mkRemovedOptionModule [ "services" "httpd" "sslServerKey" ] "Please define a virtual host using `services.httpd.virtualHosts`.") 397 ]; 398 399 # interface 400 401 options = { 402 403 services.httpd = { 404 405 enable = mkEnableOption "the Apache HTTP Server"; 406 407 package = mkOption { 408 type = types.package; 409 default = pkgs.apacheHttpd; 410 defaultText = literalExpression "pkgs.apacheHttpd"; 411 description = '' 412 Overridable attribute of the Apache HTTP Server package to use. 413 ''; 414 }; 415 416 configFile = mkOption { 417 type = types.path; 418 default = confFile; 419 defaultText = literalExpression "confFile"; 420 example = literalExpression ''pkgs.writeText "httpd.conf" "# my custom config file ..."''; 421 description = '' 422 Override the configuration file used by Apache. By default, 423 NixOS generates one automatically. 424 ''; 425 }; 426 427 extraConfig = mkOption { 428 type = types.lines; 429 default = ""; 430 description = '' 431 Configuration lines appended to the generated Apache 432 configuration file. Note that this mechanism will not work 433 when <option>configFile</option> is overridden. 434 ''; 435 }; 436 437 extraModules = mkOption { 438 type = types.listOf types.unspecified; 439 default = []; 440 example = literalExpression '' 441 [ 442 "proxy_connect" 443 { name = "jk"; path = "''${pkgs.tomcat_connectors}/modules/mod_jk.so"; } 444 ] 445 ''; 446 description = '' 447 Additional Apache modules to be used. These can be 448 specified as a string in the case of modules distributed 449 with Apache, or as an attribute set specifying the 450 <varname>name</varname> and <varname>path</varname> of the 451 module. 452 ''; 453 }; 454 455 adminAddr = mkOption { 456 type = types.str; 457 example = "admin@example.org"; 458 description = "E-mail address of the server administrator."; 459 }; 460 461 logFormat = mkOption { 462 type = types.str; 463 default = "common"; 464 example = "combined"; 465 description = '' 466 Log format for log files. Possible values are: combined, common, referer, agent, none. 467 See <link xlink:href="https://httpd.apache.org/docs/2.4/logs.html"/> for more details. 468 ''; 469 }; 470 471 logPerVirtualHost = mkOption { 472 type = types.bool; 473 default = true; 474 description = '' 475 If enabled, each virtual host gets its own 476 <filename>access.log</filename> and 477 <filename>error.log</filename>, namely suffixed by the 478 <option>hostName</option> of the virtual host. 479 ''; 480 }; 481 482 user = mkOption { 483 type = types.str; 484 default = "wwwrun"; 485 description = '' 486 User account under which httpd children processes run. 487 488 If you require the main httpd process to run as 489 <literal>root</literal> add the following configuration: 490 <programlisting> 491 systemd.services.httpd.serviceConfig.User = lib.mkForce "root"; 492 </programlisting> 493 ''; 494 }; 495 496 group = mkOption { 497 type = types.str; 498 default = "wwwrun"; 499 description = '' 500 Group under which httpd children processes run. 501 ''; 502 }; 503 504 logDir = mkOption { 505 type = types.path; 506 default = "/var/log/httpd"; 507 description = '' 508 Directory for Apache's log files. It is created automatically. 509 ''; 510 }; 511 512 virtualHosts = mkOption { 513 type = with types; attrsOf (submodule (import ./vhost-options.nix)); 514 default = { 515 localhost = { 516 documentRoot = "${pkg}/htdocs"; 517 }; 518 }; 519 defaultText = literalExpression '' 520 { 521 localhost = { 522 documentRoot = "''${package.out}/htdocs"; 523 }; 524 } 525 ''; 526 example = literalExpression '' 527 { 528 "foo.example.com" = { 529 forceSSL = true; 530 documentRoot = "/var/www/foo.example.com" 531 }; 532 "bar.example.com" = { 533 addSSL = true; 534 documentRoot = "/var/www/bar.example.com"; 535 }; 536 } 537 ''; 538 description = '' 539 Specification of the virtual hosts served by Apache. Each 540 element should be an attribute set specifying the 541 configuration of the virtual host. 542 ''; 543 }; 544 545 enableMellon = mkOption { 546 type = types.bool; 547 default = false; 548 description = "Whether to enable the mod_auth_mellon module."; 549 }; 550 551 enablePHP = mkOption { 552 type = types.bool; 553 default = false; 554 description = "Whether to enable the PHP module."; 555 }; 556 557 phpPackage = mkOption { 558 type = types.package; 559 default = pkgs.php; 560 defaultText = literalExpression "pkgs.php"; 561 description = '' 562 Overridable attribute of the PHP package to use. 563 ''; 564 }; 565 566 enablePerl = mkOption { 567 type = types.bool; 568 default = false; 569 description = "Whether to enable the Perl module (mod_perl)."; 570 }; 571 572 phpOptions = mkOption { 573 type = types.lines; 574 default = ""; 575 example = 576 '' 577 date.timezone = "CET" 578 ''; 579 description = '' 580 Options appended to the PHP configuration file <filename>php.ini</filename>. 581 ''; 582 }; 583 584 mpm = mkOption { 585 type = types.enum [ "event" "prefork" "worker" ]; 586 default = "event"; 587 example = "worker"; 588 description = 589 '' 590 Multi-processing module to be used by Apache. Available 591 modules are <literal>prefork</literal> (handles each 592 request in a separate child process), <literal>worker</literal> 593 (hybrid approach that starts a number of child processes 594 each running a number of threads) and <literal>event</literal> 595 (the default; a recent variant of <literal>worker</literal> 596 that handles persistent connections more efficiently). 597 ''; 598 }; 599 600 maxClients = mkOption { 601 type = types.int; 602 default = 150; 603 example = 8; 604 description = "Maximum number of httpd processes (prefork)"; 605 }; 606 607 maxRequestsPerChild = mkOption { 608 type = types.int; 609 default = 0; 610 example = 500; 611 description = '' 612 Maximum number of httpd requests answered per httpd child (prefork), 0 means unlimited. 613 ''; 614 }; 615 616 sslCiphers = mkOption { 617 type = types.str; 618 default = "HIGH:!aNULL:!MD5:!EXP"; 619 description = "Cipher Suite available for negotiation in SSL proxy handshake."; 620 }; 621 622 sslProtocols = mkOption { 623 type = types.str; 624 default = "All -SSLv2 -SSLv3 -TLSv1 -TLSv1.1"; 625 example = "All -SSLv2 -SSLv3"; 626 description = "Allowed SSL/TLS protocol versions."; 627 }; 628 }; 629 630 }; 631 632 # implementation 633 634 config = mkIf cfg.enable { 635 636 assertions = [ 637 { 638 assertion = all (hostOpts: !hostOpts.enableSSL) vhosts; 639 message = '' 640 The option `services.httpd.virtualHosts.<name>.enableSSL` no longer has any effect; please remove it. 641 Select one of `services.httpd.virtualHosts.<name>.addSSL`, `services.httpd.virtualHosts.<name>.forceSSL`, 642 or `services.httpd.virtualHosts.<name>.onlySSL`. 643 ''; 644 } 645 { 646 assertion = all (hostOpts: with hostOpts; !(addSSL && onlySSL) && !(forceSSL && onlySSL) && !(addSSL && forceSSL)) vhosts; 647 message = '' 648 Options `services.httpd.virtualHosts.<name>.addSSL`, 649 `services.httpd.virtualHosts.<name>.onlySSL` and `services.httpd.virtualHosts.<name>.forceSSL` 650 are mutually exclusive. 651 ''; 652 } 653 { 654 assertion = all (hostOpts: !(hostOpts.enableACME && hostOpts.useACMEHost != null)) vhosts; 655 message = '' 656 Options `services.httpd.virtualHosts.<name>.enableACME` and 657 `services.httpd.virtualHosts.<name>.useACMEHost` are mutually exclusive. 658 ''; 659 } 660 ]; 661 662 warnings = 663 mapAttrsToList (name: hostOpts: '' 664 Using config.services.httpd.virtualHosts."${name}".servedFiles is deprecated and will become unsupported in a future release. Your configuration will continue to work as is but please migrate your configuration to config.services.httpd.virtualHosts."${name}".locations before the 20.09 release of NixOS. 665 '') (filterAttrs (name: hostOpts: hostOpts.servedFiles != []) cfg.virtualHosts); 666 667 users.users = optionalAttrs (cfg.user == "wwwrun") { 668 wwwrun = { 669 group = cfg.group; 670 description = "Apache httpd user"; 671 uid = config.ids.uids.wwwrun; 672 }; 673 }; 674 675 users.groups = optionalAttrs (cfg.group == "wwwrun") { 676 wwwrun.gid = config.ids.gids.wwwrun; 677 }; 678 679 security.acme.certs = let 680 acmePairs = map (hostOpts: nameValuePair hostOpts.hostName { 681 group = mkDefault cfg.group; 682 webroot = hostOpts.acmeRoot; 683 extraDomainNames = hostOpts.serverAliases; 684 # Use the vhost-specific email address if provided, otherwise let 685 # security.acme.email or security.acme.certs.<cert>.email be used. 686 email = mkOverride 2000 (if hostOpts.adminAddr != null then hostOpts.adminAddr else cfg.adminAddr); 687 # Filter for enableACME-only vhosts. Don't want to create dud certs 688 }) (filter (hostOpts: hostOpts.useACMEHost == null) acmeEnabledVhosts); 689 in listToAttrs acmePairs; 690 691 # httpd requires a stable path to the configuration file for reloads 692 environment.etc."httpd/httpd.conf".source = cfg.configFile; 693 environment.systemPackages = [ 694 apachectl 695 pkg 696 ]; 697 698 services.logrotate = optionalAttrs (cfg.logFormat != "none") { 699 enable = mkDefault true; 700 paths.httpd = { 701 path = "${cfg.logDir}/*.log"; 702 user = cfg.user; 703 group = cfg.group; 704 frequency = "daily"; 705 keep = 28; 706 extraConfig = '' 707 sharedscripts 708 compress 709 delaycompress 710 postrotate 711 systemctl reload httpd.service > /dev/null 2>/dev/null || true 712 endscript 713 ''; 714 }; 715 }; 716 717 services.httpd.phpOptions = 718 '' 719 ; Don't advertise PHP 720 expose_php = off 721 '' + optionalString (config.time.timeZone != null) '' 722 723 ; Apparently PHP doesn't use $TZ. 724 date.timezone = "${config.time.timeZone}" 725 ''; 726 727 services.httpd.extraModules = mkBefore [ 728 # HTTP authentication mechanisms: basic and digest. 729 "auth_basic" "auth_digest" 730 731 # Authentication: is the user who he claims to be? 732 "authn_file" "authn_dbm" "authn_anon" 733 734 # Authorization: is the user allowed access? 735 "authz_user" "authz_groupfile" "authz_host" 736 737 # Other modules. 738 "ext_filter" "include" "env" "mime_magic" 739 "cern_meta" "expires" "headers" "usertrack" "setenvif" 740 "dav" "status" "asis" "info" "dav_fs" 741 "vhost_alias" "imagemap" "actions" "speling" 742 "proxy" "proxy_http" 743 "cache" "cache_disk" 744 745 # For compatibility with old configurations, the new module mod_access_compat is provided. 746 "access_compat" 747 ]; 748 749 systemd.tmpfiles.rules = 750 let 751 svc = config.systemd.services.httpd.serviceConfig; 752 in 753 [ 754 "d '${cfg.logDir}' 0700 ${svc.User} ${svc.Group}" 755 "Z '${cfg.logDir}' - ${svc.User} ${svc.Group}" 756 ]; 757 758 systemd.services.httpd = { 759 description = "Apache HTTPD"; 760 wantedBy = [ "multi-user.target" ]; 761 wants = concatLists (map (certName: [ "acme-finished-${certName}.target" ]) dependentCertNames); 762 after = [ "network.target" ] ++ map (certName: "acme-selfsigned-${certName}.service") dependentCertNames; 763 before = map (certName: "acme-${certName}.service") dependentCertNames; 764 restartTriggers = [ cfg.configFile ]; 765 766 path = [ pkg pkgs.coreutils pkgs.gnugrep ]; 767 768 environment = 769 optionalAttrs cfg.enablePHP { PHPRC = phpIni; } 770 // optionalAttrs cfg.enableMellon { LD_LIBRARY_PATH = "${pkgs.xmlsec}/lib"; }; 771 772 preStart = 773 '' 774 # Get rid of old semaphores. These tend to accumulate across 775 # server restarts, eventually preventing it from restarting 776 # successfully. 777 for i in $(${pkgs.util-linux}/bin/ipcs -s | grep ' ${cfg.user} ' | cut -f2 -d ' '); do 778 ${pkgs.util-linux}/bin/ipcrm -s $i 779 done 780 ''; 781 782 serviceConfig = { 783 ExecStart = "@${pkg}/bin/httpd httpd -f /etc/httpd/httpd.conf"; 784 ExecStop = "${pkg}/bin/httpd -f /etc/httpd/httpd.conf -k graceful-stop"; 785 ExecReload = "${pkg}/bin/httpd -f /etc/httpd/httpd.conf -k graceful"; 786 User = cfg.user; 787 Group = cfg.group; 788 Type = "forking"; 789 PIDFile = "${runtimeDir}/httpd.pid"; 790 Restart = "always"; 791 RestartSec = "5s"; 792 RuntimeDirectory = "httpd httpd/runtime"; 793 RuntimeDirectoryMode = "0750"; 794 AmbientCapabilities = [ "CAP_NET_BIND_SERVICE" ]; 795 }; 796 }; 797 798 # postRun hooks on cert renew can't be used to restart Apache since renewal 799 # runs as the unprivileged acme user. sslTargets are added to wantedBy + before 800 # which allows the acme-finished-$cert.target to signify the successful updating 801 # of certs end-to-end. 802 systemd.services.httpd-config-reload = let 803 sslServices = map (certName: "acme-${certName}.service") dependentCertNames; 804 sslTargets = map (certName: "acme-finished-${certName}.target") dependentCertNames; 805 in mkIf (sslServices != []) { 806 wantedBy = sslServices ++ [ "multi-user.target" ]; 807 # Before the finished targets, after the renew services. 808 # This service might be needed for HTTP-01 challenges, but we only want to confirm 809 # certs are updated _after_ config has been reloaded. 810 before = sslTargets; 811 after = sslServices; 812 restartTriggers = [ cfg.configFile ]; 813 # Block reloading if not all certs exist yet. 814 # Happens when config changes add new vhosts/certs. 815 unitConfig.ConditionPathExists = map (certName: certs.${certName}.directory + "/fullchain.pem") dependentCertNames; 816 serviceConfig = { 817 Type = "oneshot"; 818 TimeoutSec = 60; 819 ExecCondition = "/run/current-system/systemd/bin/systemctl -q is-active httpd.service"; 820 ExecStartPre = "${pkg}/bin/httpd -f /etc/httpd/httpd.conf -t"; 821 ExecStart = "/run/current-system/systemd/bin/systemctl reload httpd.service"; 822 }; 823 }; 824 825 }; 826}