Using Caddy as a Lightweight Web Server with Automatic HTTPS

Introduction

Caddy is a modern web server designed for simplicity and ease of use. It features automatic HTTPS by default, making it an excellent choice for users who want a lightweight yet powerful web server. This guide will walk you through installing and configuring Caddy to serve a website with automatic HTTPS.

Step 1: Installing Caddy

  1. Update your system’s package list:

    sudo apt update && sudo apt upgrade -y

  2. Install Caddy using the official package repository:

    sudo apt install -y caddy

  3. Verify that Caddy is installed correctly:

    caddy version


Step 2: Configuring Your First Caddy Website

  1. Create a new Caddyfile:

    sudo nano /etc/caddy/Caddyfile

  2. Add the following configuration:

    yourdomain.com {

    root * /var/www/html

    file_server

    }

  3. Save and exit the file.

  4. Ensure the web root directory exists:

    sudo mkdir -p /var/www/html

  5. Restart Caddy to apply the changes:

    sudo systemctl restart caddy


Step 3: Enabling Automatic HTTPS

  1. Ensure your domain’s DNS records point to your server’s IP address.

  2. Caddy will automatically obtain and renew SSL certificates from Let’s Encrypt.

  3. Check the status of your HTTPS setup with:

    sudo journalctl -u caddy --no-pager | grep -i "certificate"


Step 4: Serving a Custom Website

  1. Create an HTML file to serve:

    echo 'Welcome to Caddy.' | sudo tee /var/www/html/index.html

  2. Reload Caddy to apply changes:

    sudo systemctl reload caddy

  3. Open your browser and visit https://yourdomain.com to see the webpage.


Step 5: Running Caddy as a Reverse Proxy

  1. Modify your Caddyfile to proxy requests to an internal service:

    yourdomain.com {

    reverse_proxy 127.0.0.1:8080

    }

  2. Save the changes and reload Caddy:

    sudo systemctl reload caddy

  3. Now, Caddy will forward incoming requests to your backend service on port 8080.


Conclusion

Caddy is an excellent choice for users looking for an easy-to-configure web server with built-in HTTPS support. Its simplicity and automation make it ideal for both beginners and experienced users.