How to co-locate .md and .html files?

I am experimenting with the markdown capacities of Caddy and have a problem with .md and .html files being served at the same time.

Since I did not want my pages to end with .md (, I rewrite .html URLs to .md ones:

http://localhost:9998 {
	root /www
	markdown / {
		template default.html
	rewrite / {
		r ^(.*)\.html 
		to {1}.md

This is fine, and point to the same page as expected.

This setup, however, means that I cannot have standalone .html pages anymore (as they would be rewritten to a non-exiting .md page).

Is there a way to say “rewrite to .md except if the file actually exists, in which case do not do any rewrite” (or rewrite to itself if that helps)?

I have doubts whether my setup is reasonable (rewrite .html pages to .md) and whether having bare URLs ( which would be picked up as .md files via the ext directive would not be a wiser approach (it probably would).

Nevertheless, the question on conditional rewrite based on the existence of a file could be useful.

Howdy @WoJ, the rewrite directive actually handles this pretty neatly.

to is a space-separated list of destination paths to rewrite to (the resource to respond with); it will try each destination in sequence until the first one that exists on disk in the site root

So you can add an arbitrary number of rewrite targets, and Caddy will try each one in turn. For example:

rewrite {
  r ^(.*)\.html$
  to {1}.md {path}

If it can’t find the md file, it falls back to {path}, which is basically what it started with anyway.


Use the index directive! (if you’re serving indexes with this, that is).

index sets the list of file names that are used as “index” files. When a directory path is requested instead of a specific file, the directory is checked for existing index files. The first matching file name is served.

Welcome — Caddy Documentation

For example:

index index.html

1 Like

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