Subdomain Redirect and Reverse Proxy With Caddy

Posted by:

  • Avatar of Konstantin

    Konstantin

Let's explore an example of a Caddyfile for a reverse proxy combined with a static media file serving setup for Django (or Wagtail) website

Caddy is a very simple and very efficient proxy server. I use it for both hosting purposes (the page you're currently reading was probably served by a Caddy) and tiny experiments like a reverse proxy in a docker compose service.

The reverse proxy guide already does an excellent job of describing how to set up Caddy for this mode of working. Instead, I would like to focus on a very specific use case where Caddy is used to proxy traffic to a running Django or Wagtail website. The reason this is somewhat special is that they both expect that an external component is responsible for serving static content. So here is an example Caddyfile which can help address this:

www.example.org {
	redir https://example.org{uri}
}

example.org {
	# Handle static files from Django/Wagtail
	handle_path /media/* {
		root * /var/uploads
		file_server
	}

    # Redirect everything else to the Django/Wagtail process
	handle {
		reverse_proxy localhost:8000
	}
}

Also notice how the redirect directive includes the `{uri}` at the end, allowing the entire path of the original request to be used with the redirect. For example www.example.org/blog will then redirect to example.org/blog.

Caddy Server Logo

Tags