Header_down remove Set-Cookie header by header value

1. The problem I’m having:

We are using caddy as a reverse proxy to a backend web service. We have no control over the backend service. The backend service returns several Set-Cookie headers in random order:

  • One of them (a session id) we wish to pass through to the client
  • The rest of them we wish to remove - ie. not pass pass through to the client.

In the caddyfile we know that we can use…

reverse_proxy http://localhost:8080 {
    header_down -Set-Cookie
}

…to remove the Set-Cookie header by header name.

However in this case we wish to remove the header by header value.

For example, allow this cookie header…

Set-Cookie sessionid=<uuid>

…but do not allow this cookie header…

Set-Cookie whatever=cookievalue1234

If we use this caddyfile config…

reverse_proxy http://localhost:8080 {
    header_down -Set-Cookie
}

…then we lose all cookies including the sessionid cookie that we wish to keep.

To the question then:

Is there any way to remove cookies/headers by header value, instead of by header name?

2. Error messages and/or full log output:

n/a

3. Caddy version:

2.6.2

4. How I installed and ran Caddy:

docker run -d -p 80:80 caddy

a. System environment:

Ubuntu 22.04, Docker

b. Command:

n/a

c. Service/unit/compose file:

n/a

d. My complete Caddy config:

{
    debug
    servers :443 {
        protocols h1 h2 h3
    }
}

# Static site server
localhost:1313 {
    # Dev only - Comment the next line for production
    tls internal

    handle /htmx/* {
        reverse_proxy http://test-caddy {
            header_down -Set-Cookie
        }
    }
    file_server {
        # List of file names to use as index files. Default: index.html index.txt
        index index.html
    }
}

5. Links to relevant resources:

Thanks in advance for any help!

Something like this might work, using a regexp replacement:

header_down Set-Cookie "(^whatever=[^;]*; |; whatever=[^;]*)" ""

For example:

This might break if the cookie you want is the only value in the header though.

Also for fun, I decided to ask ChatGPT if it had an idea of a valid Golang regexp to do this. This is what it answered, which actually does make some good points – like you might want (?i) in front to replace the key case-insensitively maybe, and \b would allow simplifying the repetition in my regexp:

Haha, nice work with the chatgpt query!

Yes a regex replacement approach would work in most cases, thanks @francislavoie.

I’ll run with that if we can’t conjure up anything better.

1 Like

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