How to config try_files

1. Caddy version (caddy version):

v2.2.0 h1:sMUFqTbVIRlmA8NkFnNt9l7s0e+0gw+7GPIrhty905A=

2. How I run Caddy:

systemctl start caddy

a. System environment:

ubuntu 20.04

b. Command:

NO

c. Service/unit/compose file:

paste full file contents here

d. My complete Caddyfile or JSON config:

example.com {

        redir /html /html/
        route /html/* {
                 uri strip_prefix /html
                 file_server {
                        root /home/liupeng/html
                 }
                 try_files {path}  /index.html
        }
}

3. The problem I’m having:

The url http://xxxx.com/html just works, but if i type
http://xxxx.com/html/1 // 1 is not exits., it returns 404
so the try_files directive not works.

What’s I want is when the /1 not exists, just show index.html

4. Error messages and/or full log output:

NO

5. What I already tried:

I put try_files {path} /index.html in the file_server block, still not works. And caddy can not start succesfully.

6. Links to relevant resources:

Use the root directive rather than the root subdirective of file_server. The root directive applies globally, whereas the subdirective only applies to file_server but the try_files matcher also needs to know the root to do file lookups.

Also, I recommend using handle_path instead here, because it has implicit strip_prefix logic:

example.com {
	redir /html /html/
	handle_path /html/* {
		root * /home/liupeng/html
		try_files {path} /index.html
		file_server
	}
}
1 Like

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