使用 Caddy 和 CF 时获取访客真实 IP

本文最后更新于 80 天前, 如有失效请评论区留言.

主要记录一下ysicing.me如何用户的真实IP

前情

可能大家发现境外站用户的评论还是控制台提示信息显示的地理位置都是CFIP的归属地

如果是其他web服务器,都可以参考Cloudflare官方文档Restoring original visitor IPs, 可惜我是使用Caddy

另外,X-Forwarded-For 标头用于记录代理服务器和访问者的原始 IP,CF 会将代理 IP 添加到 X-Forwarded-For 标头中, 但是X-Forwarded-For 采用的是附加策略, 可能会导致你获取的IP不准确,因为这个可以伪造。由于这个原因,Cloudflare 建议我们使用 CF-Connecting-IPTrue-Client-IP 这两个标头,作为原始访问者的 IP, 这里我以前者CF-Connecting-IP 为例

Caddy 配置

在 Caddy 中,如果后端服务或程序支持设置从 Cf-Connecting-IP 获取真实 IP,那么就只需要在 Caddyfile 的 reverse_proxy 中 添加该标头

reverse_proxy 100.90.80.3:6666 {
    header_up CF-Connecting-IP {http.request.header.CF-Connecting-IP}
}

上面那个是简单使用,如果更加完善的话,可以考虑配置trusted_proxies

具体可以看看reverse_proxy#trusted_proxies 或者 # Global#trusted-proxies

博客设置

博客的IP获取方式需要简单调整一下

func GetIP(c *fiber.Ctx) string {
	return c.Get("CF-Connecting-IP", c.IP())
}

验证

大陆Ping

境外Ping

其他测试

Sponsor

Like this article? $1 reward

Comments

According to the relevant laws and regulations of the People's Republic of China, the comment function of the current website has been disabled. If you need to comment, please visit ysicing.me, but the comments still need to be reviewed by AI.