宝塔或Nginx环境
如果你使用的宝塔或Nginx,可以在宝塔面板或Nginx中,找到配置文件增加如下代码后,重载配置或者重启 Nginx 即可:
#CDN获取真实ip set_real_ip_from 0.0.0.0/0; real_ip_header X-Forwarded-For;
PHP语言函数方法
如果你使用的PHP语言,可以使用以下函数解决获取不到真实IP问题。
function GetClientIP(){$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];if($ip != ""){$arr = explode(",",$ip);return $arr[0];}else{return $_SERVER["REMOTE_ADDR"];}}
完整示例代码:
<?php$real_ip = '';if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);$pos = array_search('unknown', $arr);if (false !== $pos) {unset($arr[$pos]);}$real_ip = trim($arr[0]);} elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {$real_ip = $_SERVER['HTTP_CLIENT_IP'];} elseif (isset($_SERVER['REMOTE_ADDR'])) {$real_ip = $_SERVER['REMOTE_ADDR'];}