Using Caddyfile for Internal Server Routing

Pratik Chowdhury
2 min readMay 21, 2023

--

Using Caddyfiles is an easy way to add support for internal server routing for your non-React/non-SPA applications where none-the-less you would like to provide the modern SPA-style looking application

Advantages

  1. Supports Reverse Proxy for a specific route
    This allows a specific route within our application to be redirected to our backend API server
  2. Supports sending files for a specified path.
    We could use this to route the HTML files for our specific paths
  3. Supports creating a static file server
    This could help us host our static files such as CSS, images etc.

Our Website

Tis but a humble website

We will have 3 routes

  1. /facts
    This will render facts.html
  2. /
    This should obviously render index.html
  3. /api/
    The route related to our backend-API.

Caddyfile

http://localhost:8080 {
handle_path /facts {
root * /home/caddy/internalweb/facts.html
file_server
}
handle_path / {
root * /home/caddy/internalweb/index.html
file_server
}
handle_path /static/* {
root * /home/caddy/internalweb/static/
file_server
}
handle_path /api/* {
# Could be another domain/IP as well
reverse_proxy {
to localhost:8081
}
}
}

A Bad Site

Clicking on the link takes us to /facts

Why Reverse Proxy for APIs?

  1. Ensures that /api/${uri} redirects to localhost:8081/${uri}
  2. Allows hosting API and the Web content and the static site on the same domain
  3. Allows us to host multiple APIs from the same domain
  4. Makes it easier for us to modularize and split the code
    This in turn helps us write cleaner, leaner, easier to understand and better code as things are divided across barriers.
  5. For a web based developer however, by unifying things, we make everything look ever so seamless and easy

Try it out

Do try it out and see if this helps you obtain any improvements.

--

--