Caddy – Whitelist Access by IP Address

Last modified date

Comments: 0

I’ve recently been looking at Caddy as a reverse proxy server and I wanted to have an IP based whitelist to restrict access to a website Caddy is proxying. To make amending the whitelist easier, I wanted to put the IPs into a separate file.

Allow File

This is called allowlist.caddy and I place it in the same directory as my Caddyfile. Note that the allowed IP addresses listed are prefixed with not (yes, even though they allowed).

#IPs not listed here will be denied, so valid IPs are prefixed with not
@website_denied {
	not remote_ip 192.168.2.55
        not remote_ip 192.168.2.56
}

Caddyfile

To make use of your allowlist.caddy file, the server/site configuration I got working is:

{server.mylab.domain} {
	
	#Import allowed IP address list from file
	import /etc/caddy/allowlist.caddy
	error @website_denied 403
	reverse_proxy {
		to https://website
		transport http {
			tls_server_name {$server.mylab.domain}
		}	
	}

	#Return access denied page for unauthorised IP addresses
	handle_errors {
		@403 `{err.status_code} == 403`
		handle @403 {
			root * /srv
			rewrite * /403.html
			file_server
		}
	}
}

You will need to adjust the site name and reverse proxy configuration to fit your environment.

The error code handling uses Caddy to serve a static HTML page from the srv folder. If you are running Caddy in Docker, your volume mapping in docker-compose.yml might look like:

    volumes:
            - ./caddy/config:/etc/caddy
            - ./caddy/persist/data:/data
            - ./caddy/persist/config:/config
            - ./caddy/srv:/srv

Chris

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.