Automatically Obtain SSL Certificates Using Cloudflare DNS Plugin
Installing the Cloudflare Plugin
Caddy supports various DNS validation methods via its plugin system. To use DNS-01 validation with Cloudflare, you need to install the Cloudflare DNS plugin using the caddy add-package
command:
1 | sudo caddy add-package github.com/caddy-dns/cloudflare |
This command will download and install the Cloudflare DNS plugin, after which it will update the Caddy binary to include the plugin. Once the installation is complete, you’ll be able to use Cloudflare’s API for DNS-01 validation, which avoids challenges caused by Cloudflare’s proxy mode (orange cloud).
Configuring Caddyfile for DNS-01 Validation
In your Caddyfile
, configure each site to use Cloudflare for SSL certificate issuance. You can either provide your Cloudflare API Token directly in the Caddyfile
or through an environment variable like CLOUDFLARE_API_TOKEN
:
1 | export CLOUDFLARE_API_TOKEN=your_api_token |
Then, configure your Caddyfile
as follows:
1 | example.com { |
With this configuration, Caddy will automatically use Cloudflare’s DNS-01 challenge to issue SSL certificates, even if Cloudflare proxy is enabled.
Configuring Multiple Sites and Reverse Proxy
1. Static Website Configuration
Suppose you have a static website, example.com
, with its files stored under /var/www/example
. The configuration in the Caddyfile
would look like this:
1 | example.com { |
This configuration means that when someone accesses example.com
, Caddy will serve files from /var/www/example
and automatically obtain an SSL certificate for the domain.
2. Reverse Proxy Configuration
Suppose you have an application running locally (e.g., a blog) on port 3000, and you want Caddy to forward traffic to that application. In your Caddyfile
, you would use the reverse_proxy
directive like this:
1 | blog.example.com { |
This configuration will forward all traffic to blog.example.com
to your local service running on port 3000.
Blocking Direct IP Access
If you want to prevent users from accessing your website through the server’s IP address and only allow access via the domain name, you can add a rule in your Caddyfile
to check the Host
header in the request.
You can use the respond
directive to reject unauthorized access:
1 | # Block access via IP |
In this configuration:
:80
handles all HTTP requests to the IP address and returns a403 Forbidden
response, blocking access.example.com
andblog.example.com
are properly configured and will allow requests to these domains.
This ensures that users can only access the website via the correct domain and prevents direct IP access.