RuoYi-Vue3-FastAPI icon indicating copy to clipboard operation
RuoYi-Vue3-FastAPI copied to clipboard

请问,为什么自己部署后看不到在线用户的ip和位置

Open Banannna69 opened this issue 11 months ago • 2 comments

请问,为什么自己部署后看不到在线用户的ip和位置

Banannna69 avatar Apr 28 '25 07:04 Banannna69

module_admin/annotation/log_annotation.py 中oper_ip那块改成 oper_ip = request.headers.get('X-Forwarded-For') or request.client.host 就可以获取到登陆IP了,也就可以获取到地址了

SmallGarbage avatar Jun 20 '25 01:06 SmallGarbage

部署如果使用了nginx 等代理工具,IP和位置会被统一换为127.0.0.1

在nginx配置添加

    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_set_header X-Forwarded-Proto $scheme;

在代码中修改

def get_real_ip(request: Request) -> str:
    """
    获取真实IP地址
    处理顺序: X-Real-IP -> X-Forwarded-For -> client.host
    """
    x_forwarded_for = request.headers.get('X-Forwarded-For')
    if x_forwarded_for:
        # X-Forwarded-For可能包含多个IP,第一个是真实IP
        ips = [ip.strip() for ip in x_forwarded_for.split(',')]
        for ip in ips:
            if ip.lower() not in ('127.0.0.1', 'localhost'):
                return ip.split(':')[0]  # 处理可能存在的端口号

    real_ip = request.headers.get('X-Real-IP')
    if real_ip and real_ip.lower() not in ('127.0.0.1', 'localhost'):
        return real_ip.split(':')[0]

    client_host = request.client.host if request.client else '127.0.0.1'
    return client_host.split(':')[0] if client_host else '127.0.0.1'






oper_ip = self.get_real_ip(request)

liukang3014 avatar Nov 14 '25 10:11 liukang3014