Using Caddyfile for Internal Server Routing
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
- Supports Reverse Proxy for a specific route
This allows a specific route within our application to be redirected to our backend API server - Supports sending files for a specified path.
We could use this to route the HTML files for our specific paths - 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
- /facts
This will render facts.html - /
This should obviously render index.html - /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?
- Ensures that /api/${uri} redirects to localhost:8081/${uri}
- Allows hosting API and the Web content and the static site on the same domain
- Allows us to host multiple APIs from the same domain
- 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. - 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.