Blog Logo

04-Jan-2024 ~ 3 min read

Routing Requests in Caddy to API or File Server Based on Header


Caddy, a modern and efficient web server, offers flexibility in routing requests. In this guide, we’ll explore how to route requests in Caddy to either an API server or a file server based on the presence of a specific header. This enables you to handle different types of requests seamlessly.

Table of Contents

1. Introduction

Routing requests based on the presence of a specific header is a common requirement. Whether you want to direct requests to an API server or a file server, Caddy’s configuration allows for such conditional routing.

2. Installing Caddy

If you haven’t installed Caddy yet, you can do so by following the official Caddy installation instructions. Ensure you have the Caddy binary available on your system.

3. Creating the Caddyfile

Create a Caddyfile (typically named Caddyfile) with the following configuration:

example.com {
	# Route to API server if the header is set to SomeValue
	@api header X-Custom-Header SomeValue

	# Route to file server if the header is absent
	@not_api header !X-Custom-Header

	reverse_proxy @api http://localhost:8080

	handle @not_api {
		root * /mnt/data/cache
		file_server
	}
}

Replace example.com with your actual domain, adjust the header name (X-Custom-Header), configure the API server and port (localhost:8080), and set the path to the file server root (/mnt/data/cache).

This configuration uses the header directive to check for the presence of the specified header. If the header is present, requests are directed to the API server using reverse_proxy. If the header is absent, requests are handled by the file server using file_server.

4. Running Caddy

Launch Caddy with your configured Caddyfile. If your Caddyfile is in the same directory, you can run:

caddy run

Alternatively, if your Caddyfile is located elsewhere, use:

caddy run -config /path/to/your/Caddyfile

5. Testing with Header Presence

To test the conditional routing based on the presence of the header, you can use curl with the -H flag to set or omit the header. For example:

# Request to API server with the header present
curl -H "X-Custom-Header: SomeValue" http://example.com/api-endpoint

# Request to file server with the header absent
curl http://example.com/file-endpoint

Observe how the requests are routed based on the presence or absence of the specified header.

6. Conclusion

Routing requests in Caddy based on the presence of a header is a powerful feature that allows you to handle different types of requests with ease. Whether you’re managing API requests or serving files, Caddy’s configuration capabilities provide the flexibility needed for diverse scenarios. Experiment with different headers and backend configurations to meet your specific needs. Happy routing!