记录一下workerman的ip处理,由于常驻内存的原因,workerman并不能直接获取ip和使用header等php函数。本文主要记录一下获取ip的方式。
官方示例代码:
$_SERVER['HTTP_X_REAL_IP']方式
server {
listen 443;
ssl on;
ssl_certificate /etc/ssl/server.pem;
ssl_certificate_key /etc/ssl/server.key;
ssl_session_timeout 5m;
ssl_session_cache shared:SSL:50m;
ssl_protocols SSLv3 SSLv2 TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
location /wss
{
proxy_pass http://127.0.0.1:8282;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
# 这部分是利用http头透传真实客户端ip
proxy_set_header X-Real-IP $remote_addr;
}
# location / {} 站点的其它配置...
}
<?php
require_once __DIR__ . '/../Workerman/Autoloader.php';
use Workerman\Worker;
$worker = new Worker('websocket://0.0.0.0:7272');
// 客户端练上来时,即完成TCP三次握手后的回调
$worker->onConnect = function($connection) {
/**
* 客户端websocket握手时的回调onWebSocketConnect
* 在onWebSocketConnect回调中获得nginx通过http头中的X_REAL_IP值
*/
$connection->onWebSocketConnect = function($connection){
/**
* connection对象本没有realIP属性,这里给connection对象动态添加个realIP属性
* 记住php对象是可以动态添加属性的,你也可以用自己喜欢的属性名
*/
$connection->realIP = $_SERVER['HTTP_X_REAL_IP'];
};
};
$worker->onMessage = function($connection, $data)
{
// 当使用客户端真实ip时,直接使用$connection->realIP即可
$connection->send($connection->realIP);
};
Worker::runAll();
nginx配置
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://127.0.0.1:8080;
proxy_read_timeout 365d;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
或简单点
server {
server_name test.cn;
location / {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header X-Real-IP $remote_addr;
}
}
header获取
进入的$connection
$connection->header()->['x-real-ip'];
getRemoteIP
$worker->onConnect = function($connection)
{
echo "new connection from ip " . $connection->getRemoteIp() . "\n";
};
总结
测试过\(_SERVER和getRemoteIP拿到的ip并不正常,使用\)connection->header()的方式能顺利拿到x-real-ip。查看资料后是workerman4.1和3.x的区别,4.1加强了http方面。