SPA with proxies and rewrites

I’m trying to host a react SPA with Caddy that also has some proxy rewrites for the django API, but I’m getting various errors.

Sometimes it just loads the react app instead of doing the proxy redirect to django.

But currently it’s giving me ERR_TOO_MANY_REDIRECTS for any page.

What should happen:

  • /admin, /api, and /staticfiles should proxy to the hostname django.
  • All other URLs should redirect to index.html so it can be handled by react-router.
    # Main site
    example.com {
        gzip
        log stdout
        errors stdout
    
        root /app/frontend
    
        proxy /staticfiles django:8000 {
            transparent
        }
        proxy /api django:8000 {
            transparent
        }
    
        proxy /admin django:8000 {
            transparent
        }
    
        rewrite {
            to .* /index.html
        }
    }

Hi @cclloyd, I hope you don’t mind that I edited your post to put the Caddyfile in code blocks. (```)

Lets look at the locations you’ve given for the to subdirective:

.* - this is a regex pattern, but to doesn’t support these (rewrite itself does). Caddy will only execute this rewrite after checking if a literal file named .* is present on disk.

/index.html - an index file isn’t the correct way of requesting an index; instead, you should rewrite to the index itself, /. If a request to an index file makes it through Caddy, the static fileserver will redirect the client to enforce this. If you then rewrite back to the index file, a redirect loop is created.

Since you want everything to go through the index that isn’t proxied, try just rewrite .* / on its own.

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