Dwight Watson's blog

Geolocate requests with Cloudflare Transform Rules

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.

  1. Give your rule a name - Add geolocation headers is a good one,
  2. Filter which requests will need this rule to run. You can apply to all requests if required.
  3. Finally, add 2 Set dynamic headers:
  • X-IP-City has a value of ip.src.city
  • X-IP-Latitude has a value of ip.src.lat
  • X-IP-Longitude has a value of ip.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.

A blog about Laravel & Rails by Dwight Watson;

Picture of Dwight Watson

Follow me on Twitter, or GitHub.