Is it possible to rewrite/redir path returned in `X-Accel-Redirect`?

Hello, I got following usecase:

  1. User calls GET /path/1
  2. /path/1 is proxied to service A that resolves path to /redirection/path/1 and sends it in X-Accel-Redirect header.
  3. New, generated path, as it begins with redirection is redirected to external server.

internal itself works, redir itself works, but the problem is that Caddy is looking for path returned in X-Accel-Header (/redirection/path/1) and does not redirect it as specified in Caddyfile. Does it even possible to manipulate (redir/rewrite) paths that are returned in X-Accel-Proxy? Unfortunately, I can’t bypass generating
correct path so I don’t know if there’s any other method to cover my usecase.

My Caddyfile:

:8033
bind 0.0.0.0
log / stdout "{combined}"
root /home/jjlakis/caddytest

# Redirect /redirection/something to external_service/something
redir {
        if {path} starts_with /redirection
        / http://localhost:8034{rewrite_uri}
}

rewrite {
        if {path} starts_with /redirection
        r ^/redirection/(.*)$
        to /{1}
}

# Proxy /path/something to service that returns path /redirection/something
proxy /path localhost:3333 {
    without /path
    transparent
}

internal redirection

Redirection itself works:

$ curl -L -i localhost:8033/redirection/duck
HTTP/1.1 301 Moved Permanently
Location: http://localhost:8034/duck
Server: Caddy
Date: Thu, 04 Oct 2018 09:30:19 GMT
Content-Length: 61
Content-Type: text/html; charset=utf-8

HTTP/1.1 200 OK
Accept-Ranges: bytes
Content-Length: 26
Content-Type: text/plain; charset=utf-8
Etag: "pg0zk7q"
Last-Modified: Wed, 03 Oct 2018 13:45:43 GMT
Server: Caddy
Date: Thu, 04 Oct 2018 09:30:19 GMT

EXTERNAL_RESOURCE_CONTENT

Proxy server:

$ curl -i -L http://localhost:3333/duck
HTTP/1.1 200 OK
X-Accel-Redirect: /redirection/duck
Date: Thu, 04 Oct 2018 10:04:51 GMT
Content-Length: 2
Content-Type: text/plain; charset=utf-8

But this call is looking for /redirection/duck file in root instead of redirecting it:

$ curl -L -i localhost:8033/path/duck
HTTP/1.1 404 Not Found
Content-Length: 19
Content-Type: text/plain; charset=utf-8
Date: Thu, 04 Oct 2018 09:34:44 GMT
Server: Caddy
X-Content-Type-Options: nosniff

404 page not found

Thanks in advance :slight_smile:

I don’t think this will work, because of the order in which the middleware chain executes.

By the time a request gets to the point where it’s being handled by proxy, the rewrite and redir middleware is already finished processing. The X-Accel-Redirect response is handled within the proxy logic, isn’t treated like a new request, so additional rewriting and redirecting can’t take place after this stage.

https://github.com/mholt/caddy/blob/f7757da7edceb23de39e2460fd59068eb5834c93/caddyhttp/httpserver/plugin.go#L612-L644

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