Skip to main content

Web servers and networking · Advanced · 18 min

Get a wildcard certificate with a DNS-01 challenge

By Padding · Updated 18 Nov 2026
Ubuntu 26.04.1 LTS · Certbot 5.10

You will get one Let's Encrypt certificate that covers example.com and every subdomain under it with Certbot 5.10 and a DNS-01 challenge, using a Cloudflare API token that can touch one zone only, then move the challenge to a separate zone so a leaked token cannot change your real DNS records.

On this page

Let's Encrypt has to see proof that you control a name before it signs a certificate for it. The usual proof, HTTP-01, puts a file on your web server at port 80. That fails in two common cases: a wildcard name such as *.example.com, which HTTP-01 cannot cover at all, and a server that the internet cannot reach, such as an internal dashboard or a machine behind a firewall.

DNS-01 proves control a different way. Certbot puts a TXT record at _acme-challenge.example.com, Let's Encrypt looks it up, and if the value matches, the name is yours. Nothing has to listen on port 80, and the server that asks for the certificate does not even need to be the one that will use it. The cost is that Certbot needs a way to write DNS records, which means an API token for your DNS host, and that token is worth protecting.

In this tutorial you get one certificate for example.com and *.example.com with Certbot's Cloudflare plugin and a token that can edit one zone only. Then you go a step further: point _acme-challenge at a separate zone with a CNAME, give Certbot a token for that zone alone, and prove that renewal still works. Replace example.com and example-acme.net with your own names throughout.

Step 1 · Install Certbot, the Cloudflare plugin and the DNS tools

Certbot's DNS plugins ship as separate snaps. Install Certbot first if you do not have it yet (the HTTPS with Nginx tutorial covers this in more detail), then allow plugins to run as root and install the Cloudflare plugin:

Bash
sudo snap install --classic certbot
sudo ln -s /snap/bin/certbot /usr/local/bin/certbot
sudo snap set certbot trust-plugin-with-root=ok
sudo snap install certbot-dns-cloudflare

Skip the first two lines if certbot --version already works. The trust-plugin-with-root setting is a one-time consent that lets a separately installed plugin run inside Certbot, which itself runs as root.

You also need dig to look at DNS records and jq to read JSON from the Cloudflare API later on:

Bash
sudo apt-get update
sudo apt-get install -y bind9-dnsutils jq curl

Check it worked

Bash
certbot --version
sudo certbot plugins

The first line prints certbot 5.10.0 or later. The plugin list includes an entry named dns-cloudflare, next to the built-in manual, standalone and webroot. If dns-cloudflare is missing, run sudo snap connections certbot-dns-cloudflare and check that the trust setting above was applied before the plugin was installed.

Step 2 · Find the record Let's Encrypt will check

During a DNS-01 challenge, Let's Encrypt sends Certbot a random token. Certbot combines it with a fingerprint of your account key, hashes the result with SHA-256 and publishes the base64url form of that hash as a TXT record. The record name is always _acme-challenge. in front of the domain, with any *. removed. So the apex name and the wildcard share one record name:

  • example.com is checked with a TXT lookup of _acme-challenge.example.com.
  • *.example.com is checked with a TXT lookup of _acme-challenge.example.com as well.
  • api.example.com is checked with a TXT lookup of _acme-challenge.api.example.com.

A certificate for both example.com and *.example.com therefore needs two TXT values at the same name at the same moment, one per name. DNS allows several TXT records with one name, and Certbot adds both.

Before you request anything, find out which servers answer for your zone and confirm there is no stale challenge record left from an earlier attempt:

Bash
dig +short NS example.com
dig +short TXT _acme-challenge.example.com

Check it worked

The first command prints two Cloudflare name servers, names ending in .ns.cloudflare.com. If it prints your registrar's servers instead, the zone has not moved to Cloudflare yet and the plugin will not be able to help. The second command prints nothing. A leftover value does no harm, because Let's Encrypt only looks for a match, but delete stale records in the dashboard so they do not confuse you later.

Step 3 · Create an API token limited to one zone

Cloudflare's older Global API Key can change everything in your account. Certbot only needs to add and remove TXT records in one zone, so give it a token that can do exactly that.

  1. In the Cloudflare dashboard, open My Profile, then API Tokens, and select Create Token.
  2. Use the Edit zone DNS template. It grants the permission Zone, DNS, Edit.
  3. Under Zone Resources, choose Include, Specific zone, and pick example.com. Do not choose All zones.
  4. Under Client IP Address Filtering, add your server's public IP address, so the token is useless from anywhere else.
  5. Continue to the summary, create the token and copy it. Cloudflare shows the token only once.

Keep the token in your clipboard or a password manager for the next step. Do not paste it into a chat, a ticket or a shell command, because commands end up in your shell history.

Check it worked

The summary page lists one permission, Zone - DNS - Edit, and one resource, example.com. If you see more zones or more permissions, go back and remove them before you create the token. The new token also appears in the API Tokens list with the name you gave it, so you can find and delete it later.

Step 4 · Store the token where only root can read it

Create a private folder and an empty, private file first, then put the token into it. The file never exists with looser permissions, not even for a moment.

Bash
sudo install -d -m 700 /root/.secrets /root/.secrets/certbot
sudo install -m 600 /dev/null /root/.secrets/certbot/cloudflare.ini

Open the file in an editor as root:

Bash
sudo nano /root/.secrets/certbot/cloudflare.ini

Add one line, replacing the placeholder with the token you copied:

INI
dns_cloudflare_api_token = paste-your-example-com-token-here

Save and close the editor. Certbot stores the path to this file for renewals, not the token itself, so the file has to stay where it is.

Check it worked

Bash
sudo stat -c '%a %U %n' /root/.secrets/certbot/cloudflare.ini
sudo grep -c '^dns_cloudflare_api_token = ' /root/.secrets/certbot/cloudflare.ini

The first command prints 600 root /root/.secrets/certbot/cloudflare.ini. The second prints 1, which confirms the line is there without showing the token on screen. If other users can read the file, Certbot prints a warning that starts with Unsafe permissions on credentials configuration file on every run.

Step 5 · Request the wildcard certificate

Ask for both names in one request. Quote the wildcard so the shell does not try to expand * into file names:

Bash
sudo certbot certonly \
  --dns-cloudflare \
  --dns-cloudflare-credentials /root/.secrets/certbot/cloudflare.ini \
  --dns-cloudflare-propagation-seconds 30 \
  -d example.com -d '*.example.com'

On the first run Certbot asks for an email address and for you to accept the terms of service. Then it does four things:

  1. Uses the token to find the example.com zone and add two TXT records at _acme-challenge.example.com.
  2. Waits for the number of seconds given by --dns-cloudflare-propagation-seconds. The plugin's default is 10. Cloudflare usually publishes changes within seconds, so 30 is a safe margin. Other DNS hosts can need several minutes.
  3. Tells Let's Encrypt to check. Let's Encrypt looks the record up from several places, so it has to be live on every one of your name servers, not only the one nearest to you.
  4. Deletes both TXT records and saves the certificate under /etc/letsencrypt/live/example.com/.

If the check fails with an error about an incorrect or missing TXT record, raise the wait to 60 or 120 seconds and try again. While you are experimenting, add --dry-run to the same command: it runs the whole exchange against Let's Encrypt's staging service, which has much looser rate limits, and saves nothing.

Check it worked

Bash
sudo certbot certificates
sudo openssl x509 -in /etc/letsencrypt/live/example.com/cert.pem -noout -ext subjectAltName

certbot certificates lists a certificate named example.com with Identifiers: example.com *.example.com and an expiry date. The openssl line shows the Subject Alternative Name extension with both DNS:example.com and DNS:*.example.com. Within a couple of minutes, dig +short TXT _acme-challenge.example.com prints nothing again, which shows the plugin cleaned up after itself.

A wildcard covers one level only. *.example.com matches shop.example.com but not example.com itself (which is why you asked for both) and not eu.shop.example.com.

Step 6 · Move the challenge to a separate zone

The token on your server can now edit every record in example.com: your A records, your MX records, everything. If someone steals it, they can point your site or your email somewhere else. The Certbot documentation also warns that anyone who can run Certbot with these credentials can get certificates for the zone.

Let's Encrypt follows CNAME records when it looks up _acme-challenge. That lets you make _acme-challenge.example.com an alias for a name in a different zone that holds nothing but challenge records. Certbot then needs a token for that zone only. A stolen token can still be used to get a certificate for your names, so keep protecting it, but it can no longer change where your site or your email goes.

This also helps when your main zone's DNS host has no API at all, which is common with smaller registrars, including many local resellers of country-code domains. You create one CNAME there by hand, once, and all the automated changes happen in the zone that does have an API.

In the example.com zone in Cloudflare, add this record:

  • Type: CNAME
  • Name: _acme-challenge
  • Target: example.com.example-acme.net
  • Proxy status: DNS only

Set it to DNS only. A proxied record would not answer TXT lookups the way Let's Encrypt needs. A name cannot have a CNAME and other records at once, so make sure no TXT records remain at _acme-challenge.example.com. If you certify other names later, such as api.example.com, each one needs its own CNAME (_acme-challenge.api pointing to api.example.com.example-acme.net).

Now create a second token, as in the earlier step, with the Edit zone DNS template, the same IP filter, and example-acme.net as the only zone. This time store it in a curl configuration file. curl reads the header from the file, so the token never appears in a command line or the process list.

Bash
sudo install -m 600 /dev/null /root/.secrets/certbot/challenge-zone.curl
Bash
sudo nano /root/.secrets/certbot/challenge-zone.curl

Add one line, replacing the placeholder with the new token:

Text
header = "Authorization: Bearer paste-your-challenge-zone-token-here"

Check it worked

Check the CNAME, then ask the Cloudflare API what the new token can see:

Bash
dig +short CNAME _acme-challenge.example.com
sudo curl -s -K /root/.secrets/certbot/challenge-zone.curl https://api.cloudflare.com/client/v4/user/tokens/verify | jq -r .result.status
sudo curl -s -K /root/.secrets/certbot/challenge-zone.curl 'https://api.cloudflare.com/client/v4/zones?name=example-acme.net' | jq '.result | length'
sudo curl -s -K /root/.secrets/certbot/challenge-zone.curl 'https://api.cloudflare.com/client/v4/zones?name=example.com' | jq '.result | length'

dig prints example.com.example-acme.net.. The token status is active, the challenge zone is visible (1) and your main zone is not (0). That last 0 is the point of this step: with this token, example.com does not exist.

Step 7 · Switch Certbot to the delegated zone with a hook

The Cloudflare plugin always writes to the zone that matches the certificate's domain name and does not follow CNAMEs, so it cannot use the new setup. Certbot's manual plugin can: you give it a script, and Certbot runs it once per name with CERTBOT_DOMAIN and CERTBOT_VALIDATION set. Write a small script that adds and deletes the TXT record in example-acme.net:

Bash
sudo install -d -m 755 /etc/letsencrypt/acme-dns-hooks
sudo tee /etc/letsencrypt/acme-dns-hooks/cf-delegated.sh > /dev/null <<'SH'
#!/bin/sh
# Certbot manual hook: puts DNS-01 TXT records in the challenge zone.
# Usage: cf-delegated.sh add|del
set -eu

CHALLENGE_ZONE=example-acme.net   # replace with your challenge zone
CONF=/root/.secrets/certbot/challenge-zone.curl
API=${CF_API:-https://api.cloudflare.com/client/v4}
NAME="$CERTBOT_DOMAIN.$CHALLENGE_ZONE"

cf() { curl -fsS -K "$CONF" "$@"; }

ZONE_ID=$(cf "$API/zones?name=$CHALLENGE_ZONE" | jq -r '.result[0].id // empty')
if [ -z "$ZONE_ID" ]; then
  echo "This token cannot see the zone $CHALLENGE_ZONE" >&2
  exit 1
fi

case "${1:-}" in
  add)
    jq -n --arg name "$NAME" --arg content "$CERTBOT_VALIDATION" \
      '{type: "TXT", name: $name, content: $content, ttl: 60}' |
      cf -X POST -H 'Content-Type: application/json' --data @- \
        "$API/zones/$ZONE_ID/dns_records" > /dev/null
    # Wait once, after the last record, before Let's Encrypt checks.
    if [ "${CERTBOT_REMAINING_CHALLENGES:-0}" = 0 ]; then
      sleep "${PROPAGATION_SECONDS:-30}"
    fi
    ;;
  del)
    for id in $(cf "$API/zones/$ZONE_ID/dns_records?type=TXT&name=$NAME&content=$CERTBOT_VALIDATION" | jq -r '.result[].id'); do
      cf -X DELETE "$API/zones/$ZONE_ID/dns_records/$id" > /dev/null
    done
    ;;
  *)
    echo "usage: $0 add|del" >&2
    exit 2
    ;;
esac
SH
sudo chmod 700 /etc/letsencrypt/acme-dns-hooks/cf-delegated.sh
sudo sh -n /etc/letsencrypt/acme-dns-hooks/cf-delegated.sh

A few details that matter:

  • NAME is the CNAME target you created: example.com.example-acme.net. For the wildcard, Certbot sets CERTBOT_DOMAIN to example.com without the *., so both values land on the same name.
  • The script waits only after the last challenge (CERTBOT_REMAINING_CHALLENGES is 0), so a two-name certificate waits 30 seconds, not 60.
  • The cleanup deletes only records whose content matches this run's value, so it cannot remove a record that another run is still using.
  • CF_API and PROPAGATION_SECONDS are optional overrides. Leave them unset and the script uses the real API and a 30-second wait.

sudo sh -n checks the script's syntax without running it and prints nothing when it is fine.

Now ask for the certificate again with the manual plugin and your script. --cert-name example.com replaces the existing certificate rather than creating a second one, and --force-renewal makes Certbot issue it now, which also saves the new method in the renewal settings:

Bash
sudo certbot certonly \
  --manual --preferred-challenges dns \
  --manual-auth-hook '/etc/letsencrypt/acme-dns-hooks/cf-delegated.sh add' \
  --manual-cleanup-hook '/etc/letsencrypt/acme-dns-hooks/cf-delegated.sh del' \
  --cert-name example.com -d example.com -d '*.example.com' \
  --force-renewal

--preferred-challenges dns matters: without it, the manual plugin may pick HTTP-01 for the apex name. Let's Encrypt can also reuse a validation it made recently for the same account, in which case your script may not run on this request at all. The dry run in the next step uses the staging service, where nothing has been validated yet, so it is the real check of the script.

Check it worked

Bash
sudo grep -E '^(authenticator|pref_challs|manual_auth_hook|manual_cleanup_hook) ' /etc/letsencrypt/renewal/example.com.conf

You see something like:

Text
authenticator = manual
pref_challs = dns-01,
manual_auth_hook = /etc/letsencrypt/acme-dns-hooks/cf-delegated.sh add
manual_cleanup_hook = /etc/letsencrypt/acme-dns-hooks/cf-delegated.sh del

This file is what renewal reads, so from now on Certbot renews example.com through the challenge zone.

Step 8 · Prove renewal works and retire the first token

Run a full renewal against the staging service. It uses the settings Certbot just saved, runs your script for both names and saves nothing:

Bash
sudo certbot renew --dry-run

The output ends with something like Congratulations, all simulated renewals succeeded: followed by the path to fullchain.pem. The snap installs a timer that runs certbot renew twice a day. Confirm it is scheduled:

Bash
systemctl list-timers snap.certbot.renew.timer

Only once the dry run succeeds, retire the token that can edit all of example.com. Deleting the file below cannot be undone, and if a renewal file still pointed at it, that renewal would fail, so check first that nothing uses it:

Bash
sudo grep -rl cloudflare.ini /etc/letsencrypt/renewal/ || echo "no renewal file uses cloudflare.ini"

If it prints a file name, that certificate still uses the Cloudflare plugin: move it to the hook first, as in the previous step. When it prints no renewal file uses cloudflare.ini, delete the file:

Bash
sudo rm /root/.secrets/certbot/cloudflare.ini

Then, in the Cloudflare dashboard under My Profile and API Tokens, delete the first token (the one for example.com). Deleting the file alone is not enough: a copy of the token could exist in a backup or a clipboard history.

On a phone or a slow, prepaid connection, the dashboard step is the only part that needs a browser. Everything else runs on the server over SSH, and the renewals themselves need no one at all.

Check it worked

Bash
sudo ls /root/.secrets/certbot/

Only challenge-zone.curl is left. In the dashboard, the API Tokens list shows the challenge-zone token and not the example.com one. The dry run succeeded with the remaining token, so the next real renewal will too.

Next steps

  • Make renewals hard to break, with deploy hooks that reload your web server and alerts when a renewal fails: /tutorials/make-lets-encrypt-renewals-reliable.
  • Brush up on the TXT and CNAME records this tutorial relies on: /tutorials/dns-records-explained-a-cname-mx-txt.
  • See why a fresh record can take time to appear everywhere, and how to watch it happen: /tutorials/understand-dns-ttls-and-propagation-with-your-own-resolver.
  • Serve the new certificate from Nginx: /tutorials/free-https-with-lets-encrypt-and-nginx.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.