简体   繁体   中英

Apache load balancer with cookies, change ROUTEID / sticky cookie in PHP

I have 2 servers that I'm load balancing traffic with using apache load balancer. This serve's two purposes, load balancing and reverse proxy so that all hosts have the same URL. This setup is working perfectly using cookies to for stickiness.

In some cases I may need to 'force' the balancer to use a specific host (BalanceMember). This is an absolute requirement and the reason is beyond the scope of this discussion.

I have this working using PHP by simply changing the ROUTEID cookie from 1 to 2 for example. My first question is, why do I have to destroy the PHP session after I've changed the COOKIE value in order for it to take effect. The ROUTEID does not change if I don't destroy the session after changing it.

My second question is, is this the best way to achieve this goal, bearing in mind that it does work as desired.

Apache proxy.conf

<VirtualHost *:80>
Header add Set-Cookie "ROUTEID=.%{BALANCER_WORKER_ROUTE}e; Expires=-1 path=/" env=BALANCER_ROUTE_CHANGED

<Proxy "balancer://mycluster">
    BalancerMember http://myhost1.example.com/ route=1
    BalancerMember http://myhost2.example.com/ route=2

    ProxySet lbmethod=byrequests failontimeout=on
</Proxy>

ProxyPreserveHost Off

RemoteIPHeader X-Forwarded-For
RemoteIPInternalProxy 127.0.0.0/8

# Enable SSL Proxying
ProxyRequests Off
SSLProxyEngine on

ProxyPass / balancer://mycluster/ stickysession=ROUTEID
ProxyPassReverse / balancer://mycluster/

</VirtualHost>

PHP Code to change ROUTEID

session_name("my_example_session");
session_start();


ob_start();
$cookie_name = "ROUTEID";
$cookie_value = "balancer.2";
setrawcookie($cookie_name, $cookie_value, time() + (86400 * 30)); // 86400 = 1 day
ob_flush();

session_destroy();
session_write_close();

Ok, I figured it out. It turns out you don't need to destroy the PHP session. Let me take you through my leanings when dealing with cookies.

  1. Debug your cookies in your Browser, I use firebug in Firefox. This will give you a good understanding of how the cookies are stored and where. (Not doing this slowed my learning of how cookies work)

  2. Cookies use paths, so you could have the same cookie name in "/" and "/my/path" and they could have two different values. This is what caused my headache:- I set the original sticky cookie in "/" and was modifying it in "/my/path".

Replace

Header add Set-Cookie "ROUTEID=.%{BALANCER_WORKER_ROUTE}e; Expires=-1 path=/" env=BALANCER_ROUTE_CHANGED

With

Header add Set-Cookie "ROUTEID=.%{BALANCER_WORKER_ROUTE}e; path=/" env=BALANCER_ROUTE_CHANGED

$cookie_name = "ROUTEID";
$cookie_value = "balancer.2";
setrawcookie($cookie_name, $cookie_value, 0, "/");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM