Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure Caddy server for react-router

What kind of Caddyfile configuration do I need to serve a react app (created with create-react-app) with react-router correctly? Basically, domain.com/app/ (this is the root of the app) should redirect to index.html, domain.com/app/sub should redirect to index.html (routing will be done on frontend by react-router), but then again for example domain.com/app/manifest.json should not redirect to anywhere since it's an actual file that needs to be served. Then there's also domain.com/app/static/ url which should be served as is.

My current Caddyfile:

domain.com/app {
        root /server/public/app
        rewrite / {
                to {path} /
        }
}

This kind of works, but it also redirects domain.com/app/manifest.json and all domain.com/app/static/ urls too.

How to tell Caddy to look for a file in the path and if it doesn't exist then redirect to the root? The docs imply this is how the rewrite block should work, but there is something wrong in my configuration file because it does not seem to work.

I have tried many examples already but they all also redirect the /static/ folder and manifest.json etc too.

like image 604
nojs Avatar asked Sep 03 '19 13:09

nojs


Video Answer


2 Answers

The directive you're looking for is try_files.

Rewrites the request URI path to the first of the listed files which exists in the site root. If no files match, no rewrite is performed.

In your case you need:

try_files {path} /index.html
like image 101
silviot Avatar answered Oct 19 '22 19:10

silviot


This answer worked: https://stackoverflow.com/a/63688826/4615976 🙏 I also wanted to paste my whole configuration of Django + React app in here for future reference:

:443 {
    # django container running on the same host
    handle /api/* {
        reverse_proxy localhost:8080
    }
    # static files that django admin uses
    handle_path /django_static/* {
        root * /etc/caddy/html/django_static
        file_server
    }
    # react app 2
    handle_path /back_office/* {
        root * /etc/caddy/html/back_office
        file_server
        try_files {path} /index.html
    }

    # react app 1
    handle /* {
        root * /etc/caddy/html/oa
        file_server
        try_files {path} /index.html
    }

    header {
        # enable HSTS
        Strict-Transport-Security max-age=31536000;
        # disable clients from sniffing the media type
        X-Content-Type-Options nosniff
    }
    log {
        level info
        format console
    }
}
like image 33
Alex Zamai Avatar answered Oct 19 '22 18:10

Alex Zamai