简体   繁体   中英

Caddy reverse_proxy and React Router

I am unable to setup my Caddyfile to work with a React SPA app such that

  1. React router routes works
  2. Calls to /api/ (eg /api/foo ) are reverse proxied to another location

With my current Caddyfile below, React router appears to be working (visiting mysite.com/faq does not give a 404) but calls to the API backend (eg mysite.com/api/foo ) appears to be trying to load a React Router route.

How can we fix this Caddyfile ?

www.example.com {
    redir https://example.com{uri}
}

example.com {
    root * /root/example/frontend/build
    file_server
    encode gzip zstd

    reverse_proxy /api/*  api.example.com:8000

    try_files {path} /index.html
    
    tls admin@example.com

    log {
        output file /root/example/logs/access.log {
                roll_size 100mb
                roll_keep 5
                roll_keep_for 720h
        }
    }
}

Update: This Caddyfile does not work too, React router no longer works, getting an error 404 when visiting https://example.com/faq . However, reverse proxy appears to be working: The API server is getting hits when we visit https://example.com/api/foo , but its getting them incorrectly as http://api.example.com:8000/api/foo instead of http://api.example.com:8000/foo

www.example.com {
    redir https://example.com{uri}
}

example.com {
    root * /root/example/frontend/build
    file_server
    encode gzip zstd

    reverse_proxy /api/*  api.example.com:8000

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

    log {
        output file /root/example/logs/access.log {
                roll_size 100mb
                roll_keep 5
                roll_keep_for 720h
        }
    }
}

Using Caddy v2.4.3

Caddy is started using caddy start --config ~/foo/Caddyfile

I got the following to work:

http://localhost {
    root * ./trial-ui
    route {
        reverse_proxy /api/* http://127.0.0.1:8080
        try_files {path} /index.html
        file_server
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM