In production, some backend system (CRM etc) may require you send user info to them so they can know better about their customers. Though I think we can just send over the client IP addresses, some guys still require you send ISO 3166-1 country code to the backend. That's why I have the opportunity to test it out and share the procedure.

Build address-country mapping

We need to run a script to harvest the final file that HAProxy can read from. The script is created here. In order to run this script we need two seperate librarys prepared.

  • upzip: $ apt-get install unzip -y
  • iprange: compile C file in this repo and copy it to /usr/local/bin/iprange

Once they are prepared, we need a final recipe: the geoip database from Maxmind, this is a free version, you are recommended to buy a paid version to get better accuracy.
Finally, run the script and get the mapping file:
bash haproxy-geoip.sh -i GeoIPCountryCSV.zip > geoip.txt

Move the file to /etc/haproxy and it is ready to serve.

Use the mapping file to send country code

This process is a lot easier if you know how HAProxy works.
If you want to send the country code to the backend, use:

http-request set-header geoip-countrycode %[src,map_ip(/etc/haproxy/geoip.txt)] 

or if you want to send a response to the browser, use

http-response set-header geoip-countrycode %[src,map_ip(/etc/haproxy/geoip.txt)] 

Then reload or restart HAProxy. Check the results.

Reference:



This artical is created by Jialin with Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) license.
知识共享许可协议