Cloudflare反代获取用户IP

经过Cloudflare反向代理后,用户的实际IP地址在 Cf-Connecting-Ip 请求头里,如:

Host: localhost:5000
Connection: close
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
Accept-Encoding: gzip, br
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,en-US;q=0.7,en-GB;q=0.6
Cache-Control: max-age=0
Cdn-Loop: cloudflare
Cf-Connecting-Ip: 240e:350:7f20:7d00:xxxx:xxxx:xxxx:746f
Cf-Ipcountry: CN
Cf-Ray: 8a22d77a7afbbd89-LHR
Cf-Visitor: {"scheme":"https"}
Cf-Warp-Tag-Id: 94ddb410-4e1c-49e3-832d-b6ce34ffd1bd
Cookie: lang=zh-cn
Priority: u=0, i
Sec-Ch-Ua: "Not/A)Brand";v="8", "Chromium";v="126", "Microsoft Edge";v="126"
Sec-Ch-Ua-Mobile: ?0
Sec-Ch-Ua-Platform: "Windows"
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: none
Sec-Fetch-User: ?1
Upgrade-Insecure-Requests: 1
X-Forwarded-Proto: https

其中,“240e:350:7f20:7d00:xxxx:xxxx:xxxx:746f”就是用户的真实IP地址。

可以用Nginx转换成 X-Real-IpX-Forwarded-For 请求头:

# 设置 X-Real-IP 头为 Cf-Connecting-Ip 的值
proxy_set_header X-Real-IP $http_cf_connecting_ip;
# 设置 X-Forwarded-For 头,包含 Cf-Connecting-Ip 和原始的 X-Forwarded-For 值
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

已发布

分类

来自

标签:

评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注