How to return the contents of a file with the "respond" directive

Hello.
I’m trying to return the contents of a particular file by specifying a status code when a particular directory is accessed.
Is this possible with the respond directive?

1. Caddy version (caddy version):

v2.2.1 h1:Q62GWHMtztnvyRU+KPOpw6fNfeCD3SkwH7SfT1Tgt2c=

2. How I run Caddy:

I have caddy installed with xcaddy and running with systemctl.

a. System environment:

  • KVM VPS
  • Ubuntu 20.04.1

b. Command:

paste command here

c. Service/unit/compose file:

paste full file contents here

d. My complete Caddyfile or JSON config:

I set the following contents in “/etc/caddy/caddyfile”.

riku22.me{
	respond /test/* 404 {
		body /etc/caddy/html/404.html
		close
	}
}

3. The problem I’m having:

After restarting caddy with systemctl restart caddy, I accessed “riku22.me/test”.
However, of course, the file name is output instead of the contents of /etc/caddy/html/404.html.

4. Error messages and/or full log output:

No errors.

5. What I already tried:

6. Links to relevant resources:

There’s three issues.

  • You must put a space before { for your site address, spaces are significant in the Caddyfile. Otherwise, Caddy thinks your domain is literally riku22.me{

  • A matcher of /test/* will not match /test. Use /test* instead.

  • The body subdirective is supposed to be the literal content to write, not a path to a file. If you want to serve a file, then use a root + rewrite + file_server.

handle /test* {
    root * /etc/caddy/html
    rewrite * /404.html
    file_server
}

This won’t result in a 404 status though, there’s currently no way to override arbitrary responses with a specific status code.

In a real config you’ll likely use handle_errors instead to handle the case where file_server can’t find a file on disk, to write a different response:

Hello.

You must put a space before { for your site address, spaces are significant in the Caddyfile. Otherwise, Caddy thinks your domain is literally riku22.me{

I’m sorry, it seems that I accidentally erased it when I copied it.

A matcher of /test/* will not match /test. Use /test* instead.

I see.
Thank you.

The body subdirective is supposed to be the literal content to write, not a path to a file. If you want to serve a file, then use a root + rewrite + file_server.

Certainly, I confirmed that the contents of 404.html are output with the settings you taught me.

This won’t result in a 404 status though, there’s currently no way to override arbitrary responses with a specific status code.

Hmmmm, As I thought.
It was possible with Nginx, so I’d be happy if it could be realized with Caddy.
Thank you.

Yeah we looked into it a while back but it hasn’t been resolved yet.

https://github.com/caddyserver/caddy/pull/3313

This topic was automatically closed after 30 days. New replies are no longer allowed.