Just a short primer for anyone who want’s to use Apache’s new mod_md for letsencrypt certificate generation on a nixos host.

Let’s assume you have a system configuration with httpd already configured:

 {pkgs, ...}: {
    service.httpd = {
        enable = true;
        /* ..*/
    };
 }

we’ll need to override the service.httpd.package attribute with a httpd package with mod_md compiled in:

service.httpd.package = pkgs.apacheHttpd_2_4.overrideAttrs (super: {
    configureFlags = super.configureFlags + " --enable-md --enable-jansson-staticlib-deps --enable-curl-staticlib-deps ";
        buildInputs = super.buildInputs ++ (with pkgs; [ curl jansson ]);
});

then enable the watchdog and md modules:

service.httpd.extraModules = ["watchdog" "md" ]; 

Then make sure a directory is created for apache to store the certificates:

system.activationScripts.httpd_md_path = {
    text = "install -o wwwrun --mode 700 -d /var/lib/httpd/md";
    deps = [];
};

And now we start configuring mod_md:

services.httpd.extraConfig = ''
    MDStoreDir /var/lib/httpd/md

    MDCertificateAgreement https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf

    MDomain example.com auto
    
    #change to permanent when you have read the documentation!
    MDRequireHttps temporary 
'';

Add two virtualhosts for example.com, one for http and https:

services.httpd.virtualHosts = [
    { hostName = "example.com"; serverAliases = [ "www.example.com" ];  }
    { hostName = "example.com"; serverAliases = [ "www.example.com" ]; enableSSL = true; documentRoot = "/your/document/root"; }
];

After switching your machine configuration, certificates will be generated. After that, you will need to restart your httpd service once again and you’re golden!