webi-installers icon indicating copy to clipboard operation
webi-installers copied to clipboard

doc: How to host React sites with Caddy?

Open coolaj86 opened this issue 2 years ago • 3 comments

By default, React doesn't follow HTTP and HTML standards for URLs - it has a proprietary system that requires hijacking 404s, always serving index.html, and then presenting Not Found errors on the client-side instead.

We need to add an example of how to do this with Caddy to the Cheat Sheet: https://github.com/webinstall/webi-installers/tree/main/caddy

Note: we need to make sure that special routes /api/, /assets/, /js/, etc are still handled correctly - probably a "try first, then" / waterfall type of system.

For example:

  • handle /api/* => always reverse_proxy, or fail with 404
  • handle /assets/ => try root /srv/www{path}, or fail with 404
  • handle /* => try root /srv/www{path}, or serve index.html (NEVER 404)

coolaj86 avatar Oct 21 '23 19:10 coolaj86

I think it's basically to replace file_server with try_files

localhost {
    # handle API requests
    handle /api/* {
        reverse_proxy localhost:3000
    }

    # handle static assets
    handle_path /assets/* {
        rewrite * /assets{path}
        root ./build/assets/
        file_server
    }

    # handle dynamic routing
    handle /* {
        root ./build/
        file {path} /index.html
    }
}

coolaj86 avatar Oct 23 '23 03:10 coolaj86

Also, how to host a single file:

    handle /thing {
        rewrite * ./thing.txt
        root * ./build/
        file_server
    }

# or

    handle /* {
        rewrite /thing ./things/thing-1.html
        root * ./build/
        file_server
    }

coolaj86 avatar Nov 23 '23 07:11 coolaj86