PHP $_SERVER[‘SERVER_ADDR’] variable always returns 127.0.0.1
We have multiple load-balanced webserver machines running the same PHP webapp (LAMP) and I'd like to run slightly different code on each server (for testing purposes). I was hoping to use the $_SERVER['SERVER_ADDR']
super global to do something like this:
if ($_SERVER['SERVER_ADDR'] == 'XXX.XXX.XXX.XXX') {
echo "Do one thing";
} elseif ($_SERVER['SERVER_ADDR'] == 'YYY.YYY.YYY.YYY') {
echo "Do something else";
}
Unfortunately, this doesn't work because both machines are setting $_SERVER['SERVER_ADDR']
to '127.0.0.1'. How can I configure them so that $_SERVER['SERVER_ADDR']
is开发者_开发知识库 set to their public IP address?
I'm guessing the issue may be something to do with /etc/hosts
so for refererence it currently looks like this:
127.0.0.1 localhost.localdomain localhost
::1 localhost6.localdomain6 localhost6
XXX.XX.XX.XX blahblah
Update...
Oops! I neglected to consider the nginx reverse proxy in front of the web servers. All the traffic to those web servers arrives from nginx due to the following line in the nginx conf:
location / {
root /var/www/staging/current;
proxy_pass http://localhost:8880;
}
Surely it's as simple as
$ip = getHostByName(php_uname('n'));
echo $ip;
It would probably involve changing how the load-balancer connects to the server. I don't know what software this is.
You might be better off switching based on some other factor that changes between the machines. A good bet would be the hostname:
$host= php_uname('n');
switch($host) {
case 'webserver1':
...do one thing...
break;
case 'webserver2':
...do another thing...
break;
default:
die('No configuration for unknown host '.$host);
}
reverse rows in /etc/hosts
XXX.XX.XX.XX blahblah
127.0.0.1 localhost.localdomain localhost
::1 localhost6.localdomain6 localhost6
should work
Use this more accurate!
echo getHostByName($_SERVER[HTTP_HOST]);
To fix my issue, I have 3 ideas:
- I might hardcode the IP address of each server into a PHP variable in a config file that we have on each server.
- I might use the reverse proxy add forward module for Apache (mod_rpaf).
- I might change the
proxy_pass
on each server to go toXXX.XXX.XXX.XXX:8880
andYYY.YYY.YYY.YYY:8880
rather thanlocalhost
?
you should really have som server specific config that gets loaded and a server id inside. every system will behave differently and going for ip adresses, hostname is definately very error vulnerable. usually there are many applications on the server and from one day to another it might not work any longer and you will have a hard time debugging (for example some1 geths the nice idea to set up a reverse entry so mails dont get spammed any more?)
In Apache 2.4 and later $_SERVER['SERVER_ADDR'] if you are calling the server from the localhost it will return something like ::1 instead of 127.0.0.1
To solve that go to your Apache conf file and change
Listen 80
to
Listen 0.0.0.0:80
Finally make sure that your server is not behind a reverse proxy
精彩评论