Try_files and reverse_proxy

1. My Caddy version (caddy version):

2.0 release candidate 1

2. How I run Caddy:

caddy.exe start

a. System environment:

Windows 10

d. My complete Caddyfile or JSON config:

 familiengrondahl.dk {
  root C:\websites\grondahl-frontend
  file_server
  reverse_proxy /api* localhost:5000
  try_files {path} {path}/ /index.html?{query}
}

3. The problem I’m having:

I am trying to host a single page application (Angular), and redirect all calls to /api to localhost:5000 where by backend service is.
By deleting “try_files” the reverse_proxy works as it should. However without this, I cant acces familiengrondahl.dk/something, as this is not redirected to my index.html.

I would love for all request to be forwarded to index.html except calls to /api*, but can’t find any configuration to resolve this.

4. Error messages and/or full log output:

no error messages

As I would think this is a normal usecase I really hope someone can help me out :slight_smile:

For this, you’ll want to use a matcher that excludes /api*.

 familiengrondahl.dk {
    root C:\websites\grondahl-frontend

    reverse_proxy /api* localhost:5000

    @notAPI {
        not {
            path /api*
        }
        file {
            try_files {path} {path}/ /index.html?{query}
        }
    }
    rewrite @notAPI {http.matchers.file.relative}

    file_server
}

As an explanation: the try_files directive is special in that it’s a shortcut for rewrite with a try_files matcher; it doesn’t support matchers because it itself involves a matcher internally. So instead, we need to explicitly use the expanded form of try_files, i.e. using a rewrite.

1 Like

Or just use a literal route maybe? (Untested)

root C:\websites\grondahl-frontend
route {
    reverse_proxy /api* localhost:5000
    try_files {path} {path}/ /index.html?{query}
    file_server
}

Just spitballing here. But that might do what you want.

3 Likes

Yep, that’s true, that’ll probably work too. Reads better too!

To clarify, route will essentially override the order in which the directives are handled, to be the order in which they’re listed inside the block.

By default, rewrite (and therefore try_files) are ordered to be handled before reverse_proxy, because it’s very common for people to want to rewrite requests before they reach an upstream server.

2 Likes

Thanks for the quick replys.
This works perfectly, thanks, and thanks for the explenation francislavoie.

While I love Caddy so far, I am looking forward to a bit more documentation :stuck_out_tongue:

1 Like

What’s your final config look like?

And what do the docs still need?

I made a docs PR to hopefully help clarify the point about try_files and matchers:

https://github.com/caddyserver/website/pull/17

The rest of what I explained should be covered in the docs though.

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