You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过.htaccess根据CF-IPCountry请求头替换指定图片?

基于Cloudflare CF-IPCountry头实现图片的国家化替换(.htaccess方案)

需求说明

我正在使用Cloudflare,它提供名为CF-IPCountry的请求头,该头会携带用户所在国家的代码(例如德国对应DE)。需要实现:

  • 默认情况下,所有用户请求https://example.com/static/img/lang/fr.png时加载法国国旗
  • 当CF-IPCountry值为CA(加拿大)时,该请求实际返回https://example.com/static/img/lang/fr-ca.png
  • 当CF-IPCountry值为BR(巴西)时,请求pt.png返回pt-br.png

现有方案问题分析

  1. 重定向方案:原代码使用R=301永久重定向,会导致浏览器长期缓存跳转规则,即使用户后续不在加拿大,也可能继续跳转到目标图片;且地址栏URL会发生变化。
  2. 替代文件方案:通过Header set Location设置跳转仍会触发浏览器跳转,同时Content-Disposition: attachment会让图片以附件形式下载,而非在页面中直接显示,不符合需求。

正确实现方式

方案一:内部重写(URL不变,推荐)

此方式服务器内部直接返回目标图片,地址栏URL保持不变,对用户完全透明,适合需要保留原请求URL的场景:

RewriteEngine On

# 加拿大用户访问fr.png时返回fr-ca.png
RewriteCond %{HTTP:CF-IPCountry} ^CA$
RewriteRule ^static/img/lang/fr\.png$ /static/img/lang/fr-ca.png [L]

# 巴西用户访问pt.png时返回pt-br.png
RewriteCond %{HTTP:CF-IPCountry} ^BR$
RewriteRule ^static/img/lang/pt\.png$ /static/img/lang/pt-br.png [L]
  • [L]表示匹配当前规则后停止后续规则处理
  • 无需R标志,属于服务器内部资源映射,不会发送跳转响应

方案二:临时重定向(URL会变化)

如果允许用户看到地址栏URL变更,使用302临时重定向避免浏览器永久缓存:

RewriteEngine On

# 加拿大用户访问fr.png时重定向到fr-ca.png
RewriteCond %{HTTP:CF-IPCountry} ^CA$
RewriteRule ^static/img/lang/fr\.png$ https://example.com/static/img/lang/fr-ca.png [L,R=302]

# 巴西用户访问pt.png时重定向到pt-br.png
RewriteCond %{HTTP:CF-IPCountry} ^BR$
RewriteRule ^static/img/lang/pt\.png$ https://example.com/static/img/lang/pt-br.png [L,R=302]
  • 禁止使用R=301,永久重定向会导致浏览器缓存跳转规则,无法根据用户后续位置变化动态调整

内容的提问来源于stack exchange,提问作者Andres SK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 09:23:10