HAProxy community

Dynamic set-cookie value on redirect


#1

I want to set dynamic cookie value(from rand function) while doing re-direction. First i tried set-cookie option like following:

http-request redirect code 307 location %[capture.req.uri] set-cookie test=%[rand(20)]

but this gives me:

HTTP/1.1 307 Temporary Redirect
Cache-Control: no-cache
Content-length: 0
Location: /test
Set-Cookie: test=%[rand(20)]; path=/;

after reading haproxy source code i found a workaround, adding Set-Cookie header after location with \r\n works perfectly.

http-request redirect code 307 location %[capture.req.uri]\r\nSet-Cookie:\ test=%[rand(20)]

output:

HTTP/1.1 307 Temporary Redirect
Cache-Control: no-cache
Content-length: 0
Location: /test
Set-Cookie: test=16

I want to know whether this is a good practice?.


#2

I need this as well.

At first I thought I could use a http-request add-header command to do this, but that doesn’t work. After finding this: https://www.mail-archive.com/haproxy@formilux.org/msg25061.html I think your hack is the only way to do it. Although I definitely think it should have a way to add headers using log-format syntax.


#3

Lua way

Cfg:
set your cookie and location headers

use_backend redirectWithSetCookie

backend redirectWithSetCookie
http-request use-service lua.redirectWithSetCookie

Lua:
core.register_service(“redirectWithSetCookie”, “http”, function(applet)
applet:set_status(301)
applet:add_header(“set-cookie”, applet.headers[‘set-cookie’][0])
applet:add_header(“location”, applet.headers[‘location’][0])
applet:start_response()
applet:send(’’)
end)