Show IP Info of Your Visitor

Only backend. Safe and JS-free.

As you can see in this site, visitor's IP address and corresponding country & city are shown in the footer section. And if you take a look at source code of HTML, you may find that the information is hard-coded, instead of using some JavaScript to generate at frontend. So, here is the question: how to do so?

Why not frontend?

First, we should answer this question. Using frontend solution may be easy (you only need to tweak frontend layout, without necessity of dealing with backend data), but it usually (if not always) depends on some third-party services. That means visitors have to send requests to that third-party, and only after that you can display IP info on your site. Certainly this is bad for privacy.

Besides, most third-party services have limit on request frequency, so you may need to pay to get desired service, which is just another disadvantage.

How to do that in backend?

In fact, it's quite easy. Your web server knows both visitor's IP address and the page to display. You only need to provide the placeholder of IP info in that page and give web server database to find IP associated information.

Take my site as example (which uses NGINX). First, you need some NGINX modules like ngx_http_sub_module and ngx_http_geoip2_module. Second, you should have an IP info database. You may download one from dbip, which is free of charge. Remember to download the MMDB format. Suppose its name is ip.mmdb, then you can use the following NGINX config to display visitor's IP info.

http {
  geoip2 /path/to/ip.mmdb {
    $geoip2_city city names en;
    $geoip2_country country names en;
  }
  server {
    listen xxx;
    server_name xxx;
    root xxx;
    sub_filter %IP% $remote_addr;
    sub_filter %COUNTRY% $geoip2_country;
    sub_filter %CITY% $geoip2_city;
    location ~ \.html$ {
      add_header Cache-Control no-store;
    }
  }
}

Now you only need to set %IP% as placeholder of visitor's IP address in your HTML, and NGINX will replace it with real one when serving the page. The same is with %COUNTRY% and %CITY%.

Please note that it's necessary to set Cache-Control header to no-store, so that when visitor's IP address changes, the IP info will update correctly.