How I fetched country and city information from the user’s HTTP request?

Prasanjit Mishra
2 min readAug 19, 2021

--

Problem Statement: We wanted to run a campaign and give additional discounts to users based on their geo-location.

Solution: To solve this, we need to fetch geo-location(Country and City information) from the HTTP request and then apply the business logic based on the country and city codes.

So the HTTP request that is coming may initiate from a client’s web browser, and finally, it comes via the load balancer to the Nginx web server. It may happen that in a microservice architecture, the request may come via multiple services before reaching the load balancer of your service. So I will be having a list of Ip addresses from starting to end in the X-Forwarded-For variable. How I am gonna find the first Ip address from where the request is originated?

I used the Nginx Geo module to solve this problem. We will install the Geo module in the Nginx server and will use Country and City mmDB(Max mind database). Nginx will fetch the Country and City information from the mmDB.

Nginx Configurations:

Explanation

  1. Download the GeoIP2-Country and GeoIP2-City max-mind databases from the source(Max-mind database) and keep this in a location, in the above example /usr/share/GeoIp
  2. X-Forwarded-For is the variable where the list of comma-separated IP addresses from the client to the server will be found. We have to find the first IP address from the X-Forwarded-For and set this as $realip
  3. Then Nginx will fetch the country code, country name and city name from the $realip, which we fetched earlier and save that in $geoip2_data_country_code, $geoip2_data_country_name, $geoip2_data_city_name respectively.

Now we will set these values in the request header. Let's see how we can do it.

location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header COUNTRY_CODE $geoip2_data_country_code;
proxy_set_header COUNTRY_NAME $geoip2_data_country_name;
proxy_set_header CITY_NAME $geoip2_data_city_name;
}

As the values are set in the request header, we can now fetch at the code level from the request headers. Country code can be fetched from the header COUNTRY_CODE , similarly Country name and City name from COUNTRY_NAME and CITY_NAME respectively.

Thank you for your interest. Happy learning.

About The Author:

Prasanjit Mishra, Tech Enthusiast

References:

--

--