3 step file delivery and reverse proxy

1. Caddy version (caddy version):

2.4

2. How I run Caddy:

caddy run

a. System environment:

Ubuntu VM

b. Command:

sudo caddy run

d. My complete Caddyfile or JSON config:


dub.domain.net
        {
                route * {
                        root * path/to/build/dir
                        try_files {path} try_files /index.html reverse_proxy 127.0.0.1:1338
                        file_server

                }

        }

3. The problem I’m having:

I’m in the process of switching my deploymentprocess over to hosting all static files via caddy and also let it taking care of the reverse-proxy process.
The main issue I got now Is that I’m looking for the following behaviour:

  1. Check if path is /, in this case serve the index.html
  2. If there is a path, serve the file on that path, if it exists.
  3. If there is no file, reverse proxy everything the a server running on port 1338

I have a hard time getting to that logic, maybe someone can give me a hint in the right direction.

4. Error messages and/or full log output:

No errors, only wrong files delivered.

5. What I already tried:

I’m trying different setups. I’m mainly thinking about creating one route for /, and then doing the rest with the try_files directive.

I was able to solve it with some searching arround and came up with this working solution:

mydomain.net
{
root * /path/to/build/dir
route / {
try_files /index.html
file_server
}

                route * {
                        @notStatic {
                                not {
                                        file {
                                                try_files {path}
                                                }
                                }
                        }

                        reverse_proxy @notStatic 127.0.0.1:1338
                        file_server
                }

        }

What you have there isn’t valid syntax. The try_files directive doesn’t take other directives as arguments, it just takes file paths to try on disk, and will do a rewrite to that path for the first one that exists.

To do what you want, you should use request matchers and handle blocks.

example.com {
	root * /path/to/build/dir

	@fileExists file
	handle @fileExists {
		file_server
	}

	handle {
		reverse_proxy 127.0.0.1:1338
	}
}

The handle directive is used to make the handling of these two paths mutual exclusive, and a handle without a matcher will always be the last one tried.

1 Like

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