Search code examples
phpapachehttp-proxymod-proxyhttpcookie

How to set the server name on a load balanced Apache+PHP server?


I set up a load-balanced Apache server using this tutorial, and everything is working fine from the Apache's side. I have a load balancer with mod_proxy, and two webheads which serve the request in practice.

But I tried to run my PHP application on them, and there is an issue with setting cookies. While investigating, I found the server name is set to the IP address of the server (not the real server name I set in httpd.conf). This is the command I used for setting the cookie;

setcookie("mycookie", $value, time() + 86400, "/", $_SERVER['SERVER_NAME'], false, true);

The reason that I used $_SERVER['SERVER_NAME'] here is, my application for each client has a separate address (e.g client1.xyz.com, client2.xyz.com, etc), so the server name is not consistent for all users.

If I echo the value if the $_SERVER['SERVER_NAME'], it shows the IP address of the server, not the server name. Therefore, the cookie is lost when I switch between servers.

How can I set the server name on the webheads of the cluster?


Solution

  • I found the answer myself. It can be done by setting ProxyPreserveHost in the load balancer (inside Proxy directive). This way, the client header will be passed by the load balancer to the workers.

    ProxyPreserveHost On