I'm using Cloudflare, which has a request header named CF-IPCountry
that holds the value of the country the user is visiting from. Example: DE
for Germany.
I need to serve a different image in certain cases. For example, for all users, the France flag will be loaded with this request: https://example.com/static/img/lang/fr.png
But, if the CF-IPCountry
request header value is CA
(Canada), then all requests for https://example.com/static/img/lang/fr.png
should actually load this other file https://example.com/static/img/lang/fr-ca.png
I've detected those cases for these visitors:
CA
: canadians should load fr-ca
instead of the french flag fr
BR
: brazilians should load pt-br
instead of the portuguese flag pt
How can this logic be implemented on my .htaccess
file?
Update
Based on @CBroe's recommendation, I've come up with 2 approaches.
1. Redirecting:
RewriteEngine On
RewriteCond %{HTTP:CF-IPCountry} ^CA$
RewriteRule ^static/img/lang/fr\.png$ https://example.com/static/img/lang/fr-ca.png [L,R=301]
2. Serving alternate file:
SetEnvIf CF-IPCountry ^CA$ ServeAlternativeFile=true
<FilesMatch "^static/img/lang/fr\.png$">
Header set Location "/static/img/lang/fr-ca.png" env=ServeAlternativeFile
Header set Content-Disposition "attachment; filename=fr-ca.png" env=ServeAlternativeFile
</FilesMatch>
Solution
Based on @CBroe's recommendation, I came up with 2 approaches.
1. Redirecting:
RewriteEngine On
RewriteCond %{HTTP:CF-IPCountry} ^CA$
RewriteRule ^static/img/lang/fr\.png$ https://example.com/static/img/lang/fr-ca.png [L,R=301]
2. Serving alternate file:
SetEnvIf CF-IPCountry ^CA$ ServeAlternativeFile=true
<FilesMatch "^static/img/lang/fr\.png$">
Header set Location "/static/img/lang/fr-ca.png" env=ServeAlternativeFile
Header set Content-Disposition "attachment; filename=fr-ca.png" env=ServeAlternativeFile
</FilesMatch>