Nginx 反向代理客户端获取真实IP

项目使用了nginx做反向代理,客户端一直获取不到真实ip,奇怪的是本地开发不存在这个问题,线上存在这个问题,一顿排查后发现线上使用了分布式部署,对登录做了统一转发,也就是登录转发没有配置 proxy_set_header X-Real-IP $remote_addr;

 server {
        listen               88;
        server_name          localhost;
        index index.php index.html index.htm default.php default.htm default.html;
        root  /项目目录/;
        location /api {
            proxy_pass http://127.0.0.1/api;
            proxy_set_header  Host  $host;
            proxy_set_header  X-Real-IP  $remote_addr;
            proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;
        }
        location / {
                   try_files $uri $uri/ /index.html;
            if ($request_filename ~* ^.*?.(html|htm)$) {
                add_header Cache-Control "private, no-store, no-cache, must-revalidate, proxy-revalidate";
             }
        }
		location /api/auth/login {
            proxy_pass http://127.0.0.1/api/auth/login;
        }
        location /api/static {
            proxy_pass http://127.0.0.1/static/;
        }
        location /design {
            proxy_pass http://127.0.0.1/api/common/design;
        }

    }

location /api/auth/login {
     proxy_pass http://127.0.0.1/api/auth/login;
}
修改为
location /api/auth/login {
	proxy_pass http://127.0.0.1/api/auth/login;
	proxy_set_header  Host  $host;
	proxy_set_header  X-Real-IP  $remote_addr;
	proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;
}

问题解决 客户端获取真实ip

    function get_client_ip() {
        $ipaddress = '';
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            // 如果有多个 IP 地址,取第一个
            $ipaddress = trim(current(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])));
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            // 如果没有 X-Forwarded-For 头,使用 REMOTE_ADDR
            $ipaddress = $_SERVER['REMOTE_ADDR'];
        }
        return $ipaddress;
    }

$clientIp = get_client_ip();

码上有钱的博客
请先登录后发表评论
  • latest comments
  • 总共1条评论
码上有钱的博客

床头的枕边书 码上有钱的博客

2024-05-04 19:49:56 回复