Geolocate requests with Cloudflare Transform RulesMay 24, 2022
In an earlier post I wrote about how to get the rough latitude/longitude of a visiting IP using Cloudflare workers. Since then Cloudflare has made improvements which made this easier to set up (you can do it through the dashboard) and free (tranform rules are included and don't use workers).
Under your Cloudflare site navigate to
Transform Rules. Then create a transform rule that modifies the request header.
- Give your rule a name -
Add geolocation headersis a good one,
- Filter which requests will need this rule to run. You can apply to all requests if required.
- Finally, add 2
X-IP-Cityhas a value of
X-IP-Latitudehas a value of
X-IP-Longitudehas a value of
Save and deploy the rule and those headers will now be available to the applied requests. You can see a complete list of available dynamic values here and add more that are appropriate for your app. Generally speaking you have more options and control with Workers, but this gives you a simple and easy implementation.
Finally - don't forget if you only need the country code you can enable Cloudflare IP Geolocation in the dashboard which will add a
CF-IPCountry header to the request automatically - nothing else required.