首页 > 解决方案 > Caddy reverse_proxy 和 React 路由器

问题描述

我无法设置我Caddyfile使用 React SPA 应用程序,这样

  1. 反应路由器路由工作
  2. /api/对(eg ) 的调用/api/foo被反向代理到另一个位置

在下面我当前的Caddyfile情况下,React 路由器似乎正在工作(访问mysite.com/faq不会给出 404),但对 API 后端的调用(例如mysite.com/api/foo)似乎正在尝试加载 React 路由器路由。

我们如何解决这个问题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
        }
    }
}

更新:这Caddyfile也不起作用,React 路由器不再起作用,访问时收到错误 404 https://example.com/faq。但是,反向代理似乎正在工作:API 服务器在我们访问时得到命中https://example.com/api/foo,但它错误地获取它们http://api.example.com:8000/api/foo而不是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
        }
    }
}

使用球童 v2.4.3

球童开始使用caddy start --config ~/foo/Caddyfile

标签: reactjsreact-routersingle-page-applicationreverse-proxycaddyfile

解决方案


我得到了以下工作:

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

推荐阅读