Setting Caddy to be used with a SPA

Hi guys,

I would like use Caddy in my new project. Which is a SPA built with ReactJS. I am using React-Router and all URLs must go to index.html. For example:

https://myproject.com/ → index.html
https://myproject.com/user/edit → index.html

But what happing is that when I try it I get a 404. Because of course there isnt a user/edit/index.html folder structure in my public folder.

Any one of you can help me ?!

Thx!

Carlos.

Take a look at the rewrite middleware - it should make it pretty easy to turn everything into index.html.

i supposed to be using that middleware. And my Caddy File look like:

rewrite { regexp (.*) to / }
But I get this error:

(master) λ caddy 2016/10/17 16:44:34 Caddyfile:2 - Parse error: Unknown directive 'regexp'

:frowning:

The first line of your Caddyfile must always contain the address of the site you want to serve. :wink:

The Caddyfile always starts with the address of the site to serve

Do you mean something like “localhost:3000”?!

I put it but is the same 404 :frowning:

Really I am the first who want to use Caddy for a SPA ?!

Your rewrite is wrong it should be something like this:

rewrite { to {path} {path}/ /index.html }

Make sure you read the docs :slight_smile:

1 Like

Thx! That work great :slight_smile:

I used this rewrite for my SPA too. However I also want to preserve the original path.

For that I tried this:
to {path} {path} /index.html{uri}
which gives me a 503 error. redir does the same. Is there a way to redirect to index.html but then allow the browser to route the remainding path (html5 style)?

Sounds perfectly correct to me. The file /index.html/user/edit doesn’t exist as a file so is not going to be rewritten.

Perhaps you want to rewrite to a query string?

rewrite {
    to {path} {path}/ /index.html?{uri}
}

Or, a fragment?

rewrite {
    to {path} {path}/ /index.html#{uri}
}

Thanks, but no, I really mean that Caddy should always return index.html’s content regardless of the url. The browser will then do frontend routing.

In Apache this is working for me using the RewriteEngine. Here are the docs for this setup for different servers:

And that’s exactly what I told you how to do previously. It matches the angular docs right there. If its not a file or directory then redirect the user to index.html.

rewrite {
    to {path} {path}/ /index.html
}

Nevermind, had the wrong config active. :slight_smile:

@zwack what did you end up with?

It works like suggested. I now use this config:

rewrite {
    if {path} not_match ^/api
    to {path} {path} /index.html
}
1 Like

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