Serve first markdown file in directory with a rewrite or markdown directive


I love the automatic markdown handling, it’s almost everything I need to ditch my CMS and just serve a hierarchy of text files as my site. One thing that I couldn’t figure out though. Is it possible to tell caddy to serve the first markdown file it finds in a directory? So I could name my text files anything, and Caddy would still serve a markdown file in a directory as the index file.

Like these steps:

  1. User browses to
  2. /posts/something contains An and
  3. Caddy looks at the markdown files and picks An because it’s the first one in natural ordering
  4. Caddy serves that rendered markdown file for the url

The way I have it working now is that all directory urls get served through an index.php. The php script globs the markdown files in the dir and asks caddy for the first markdown file in the dir. It’s simple enough, but I feel like I’m missing something, that there could be a better way to do this.

Here’s my Caddyfile, nothing special

localhost:3000 {
  root .
  rewrite /404 {
    status 404
  rewrite / {
    ext    /
    to     /index.php
  markdown / {
    template template.html
  fastcgi / php

And the php file is basically like: echo curl(""). (There’s some checks and stuff in the actual script, but I shortened the script here to the relevant bits)

$host = $_SERVER['HTTP_HOST'];
$dir = $root . $uri;
$files = glob($dir . '/*.md');
if ($files) {
  $url = $host . $uri . '/' . rawurlencode(basename($files[0]));
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  echo curl_exec($ch);
} else {
  //curl 404 page

Is there like a proper way to do this? Is this madness? :smiley:

I suppose the “proper” way to do it is to name the file :slight_smile: This is surely the simplest! And index.html will be automatically rendered when requesting the directory instead of a specific file.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.