How to Host a Website in Caddy on Ubuntu

Configuration

By Chandrashekhar Fakirpure

Updated on Jan 27, 2024

In this article, we'll explain how to host a website in Caddy. Before moving following, first set up domain’s A DNS record at your domain registrar.

Now, open Caddy’s configuration file and add your domain name and change website’s root directory.

nano /etc/caddy/Caddyfile

Replace :80 with your domain name and change the site root to /var/www/hostnextra.com as, add log {} to record log in specific file. Here we can enable Zstandard and Gzip compression (with Zstandard implicitly preferred, since it is first):

It should look like:

hostnextra.com {
    root * /var/www/hostnextra.com

    file_server
    encode zstd gzip

    log {
        output file /var/log/caddy/hostnextra.log
    }        
}

Note: Replace hostnextra.com with your domain name. If you have custom or different website root directory, replace /var/www/hostnextra.com with your root directory path.

Once you done with the changes, we test the Caddy configurations for errors using following command: 

caddy validate

If you get any error check with the line number mentioned in error message. If everything looks good, reload the Caddy service to reflect the changes.

caddy reload

Now, create a index.html file in /var/www/html/hostnextra.com using following command:

echo '<!doctype html><head><title>Hello from Caddy! Ubuntu</title></head><body><h1 style="font-family: sans-serif">This page is being served via Caddy</h1></body></html>' | sudo tee /var/www/hostnextra.com/index.html

Finally, refresh the page in your browser and you will see our newly created index.html.

Note: It won't work on local environment, because Caddy automatic HTTPS. 

In this article, we have seen how to host a website in Caddy on Ubuntu 22.04.