Using CGI scripts in Caddy

A quick tip on how to compile and configure Caddy for the purpose of running CGI scripts.

This guide assumes Debian operating system, and that Go and Caddy are already installed.

  1. Verify that the go command is working correctly:
go version
  1. Exclude the preexisting Caddy install from system updates to prevent later overriding of the newly compiled Caddy binary:
apt-mark hold caddy
  1. Install xcaddy:
sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https

curl -1sLf 'https://dl.cloudsmith.io/public/caddy/xcaddy/gpg.key' | sudo gpg --dearmor -o /usr/share/keyrings/caddy-xcaddy-archive-keyring.gpg

curl -1sLf 'https://dl.cloudsmith.io/public/caddy/xcaddy/debian.deb.txt' | sudo tee /etc/apt/sources.list.d/caddy-xcaddy.list

sudo apt update && sudo apt install xcaddy
  1. Create a temporary directory:
mkdir /xcaddy-temp 
cd /xcaddy-temp 
  1. Compile Caddy with the CGI module:
xcaddy build master --with github.com/aksdb/caddy-cgi/v2@v2.2.5

Replacing 2.2.5 with latest release number from the CGI for Caddy Github releases page.

  1. Stop Caddy service:
systemctl stop caddy
  1. Move the previous Caddy binary to a temporary backup folder, in case the compiled version fails to work correctly:
mv -i /usr/bin/caddy /xcaddy-temp/caddy-backup 
  1. Replace Caddy executable:
mv -i /xcaddy-temp/caddy /usr/bin/caddy
  1. Start Caddy service:
systemctl start caddy 
  1. Verify that Caddy service is working correctly:
systemctl status caddy
  1. If you have any appplications or websites served by Caddy, verify that they are still working correctly.

  2. Remove the temporary directory:

rm -rf /xcaddy-temp 
  1. Go into the folder containing Caddyfile:
cd /etc/caddy
  1. Edit Caddyfile:
sudo nano /etc/caddy/Caddyfile
  1. Add following lines at the top of Caddyfile:
{
    order cgi before respond
}
  1. Add configuration for the specific CGI script(s) to Caddyfile as per the CGI for Caddy syntax.

  2. Format Caddyfile:

sudo caddy fmt --overwrite
  1. Validate Caddyfile:
sudo caddy validate

Make sure there’s no errors before next steps.

  1. Restart Caddy:
sudo systemctl restart caddy
  1. Verify that Caddy service is working correctly:
sudo systemctl status caddy
  1. Verify that the CGI script is working correctly.