Geolocate requests with Cloudflare Transform Rules
This blog post was originally published a little while ago. Please consider that it may no longer be relevant or even accurate.
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 Rules
-> Transform Rules
. Then create a transform rule that modifies the request header.
- Give your rule a name -
Add geolocation headers
is a good one, - Filter which requests will need this rule to run. You can apply to all requests if required.
- Finally, add 2
Set dynamic
headers:
X-IP-City
has a value ofip.src.city
X-IP-Latitude
has a value ofip.src.lat
X-IP-Longitude
has a value ofip.src.lon
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.