...
ONe of my main reasons for moving to HAProxy was to enable HTTP session management at as little cost as possible. The following is a description of how to enable this in HAProxy.
If you want web sessions to have persistent connections to the same server, you can use a balance
algorithm such as
hdr, rdp-cookie, source, uri, orurl_param.
If your implementation requires the use of the
leastconn
,roundrobin
, orstatic-rr
algorithm,
you can implement session persistence by using server-dependent cookies.
To enable session persistence for all pages on a web server, use the cookie
directive to define the name of the cookie to be inserted and add the cookie
option and server name to the server
lines, for example:
Code Block | ||
---|---|---|
| ||
cookie WEBSVR insert server websvr1 192.168.1.71:80 weight 1 maxconn 512 cookie 1 check server websvr2 192.168.1.72:80 weight 1 maxconn 512 cookie 2 check |
HAProxy includes an additional Set-Cookie:
header that identifies the web server in its response to the client, for example: Set-Cookie: WEBSVR=
. If a client subsequently specifies the N
; path=page_path
WEBSVR
cookie in a request, HAProxy forwards the request to the web server whose server cookie
value matches the value of WEBSVR
.
The following example demonstrates how an inserted cookie ensures session persistence:
Info | ||
---|---|---|
| ||
$ while true; do curl http://10.0.0.10; sleep 1; done |
To enable persistence selectively on a web server, use thecookie
directive to specify that HAProxy should expect the specified cookie, usually a session ID cookie or other existing cookie, to be prefixed with theserver cookie
value and a~
delimiter, for example:
Code Block | ||
---|---|---|
| ||
cookie SESSIONID prefix
server websvr1 192.168.1.71:80 weight 1 maxconn 512 cookie 1 check
server websvr2 192.168.1.72:80 weight 1 maxconn 512 cookie 2 check |
If the value of SESSIONID
is prefixed with a server
cookie
value, for example: Set-Cookie: SESSIONID=
, HAProxy strips the prefix and delimiter from the N
~Session_ID
;SESSIONID
cookie before forwarding the request to the web server whose server cookie
value matches the prefix.
The following example demonstrates how using a prefixed cookie enables session persistence:
Info | ||
---|---|---|
| ||
$ while true; do curl http://10.0.0.10 --cookie "SESSIONID=1~1234;"; sleep 1; done |
A real web application would usually set the session ID on the server side, in which case the first HAProxy response would include the prefixed cookie in the Set-Cookie:
header.