Redirect to root with rewrite

I want every url except real files and /api rewritten to /index.html.

* {
  rewrite / {
    if {path} not_starts_with /api
    to {path} {path}/ /index.html
  }
  proxy /api https://r.datenknoten.me
  root /var/www

  tls off
}

If I access / I get the index.html, but if I try to access /foo/bar/ I get a redirect to /. With my config I would expect that /foo/bar/ would serve the index.html. /api returns the API correctly.

I dont get any error logs, because from the caddy config everything seems to fine?!

Hi @enko, welcome to the Caddy community.

I can’t see anything in that Caddyfile that would be issuing a redirect.

Could you add log / access.log "{common} - {rewrite_uri_escaped}" to your Caddyfile and then give us the output of curl -i */foo/bar as well as the resulting log?

Hi @Whitestrake,

thanks for your warm welcome!

My Caddfile looks like this now:

* {
  log / stdout "{common} - {rewrite_uri_escaped}"
  rewrite / {
    if {path} not_starts_with /api
    to {path} {path}/ /index.html
  }
  proxy /api https://r.datenknoten.me
  root /var/www

  tls off
}

And the corresponding log entry looks like this:

192.168.99.1 - - [05/Jul/2017:13:44:47 +0000] "GET /foo/bar HTTP/1.1" 301 36 - %2Findex.html

curl output looks like this:

λ curl -i http://192.168.99.100:8080/foo/bar
HTTP/1.1 301 Moved Permanently
Location: /
Server: Caddy
Date: Wed, 05 Jul 2017 13:48:12 GMT
Content-Length: 36
Content-Type: text/html; charset=utf-8

<a href="/">Moved Permanently</a>.

I should note that I use the docker container from the docker hub.

Thanks for your time!

:man_facepalming:

No idea why I gave you the escaped version to use. Oh well, small matter.

Turns out, Caddy’s static fileserver is handling the request for /index.html with a permanent redirect to the canonical /, which is how the client should request an index. (more info, I see this is a recent change)

You can fix this by changing your to subdirective:

rewrite {
  if {path} not_starts_with /api
  to {path} {path}/ /
}

I wonder if we will see a few more people pop up with this problem soon, I believe rewriting to a specific index file is quite common.

3 Likes

Thanks a lot! That fixed the issue!

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