How to 302 redirect based on geo-ip in nginx
I want my all my users have the fastest loading speed when visiting my website chinesefoodlab.com, so it is better to use server in the same location as users. However, all websites hold by server in China mailand needs ICP file and my chinesefoodlab.com cannot finish ICP filing in China cause it contains “chinese” characters. So I registered another domain cnfoodlab.com and finished ICP filing. I want to use chinesefoodlab.com as main domain, so I need to redirect users from China mainland to cnfoodlab.com to give them the best service. And this tutorial is to record how to do it.
How to 302 redirect based on geo-ip in nginx
Download free geo-ip database from maxmind.com
Register an account in maxmind.com
Then you will receive an email which says “A New MaxMind License Key Was Generated For Your Account”, you can login to your account portal using the link in this email.
Download Config file in account portal, which should like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14# GeoIP.conf file for `geoipupdate` program, for versions >= 3.1.1.
# Used to update GeoIP databases from https://www.maxmind.com.
# For more information about this config file, visit the docs at
# https://dev.maxmind.com/geoip/updating-databases.
# `AccountID` is from your MaxMind account.
AccountID 1234567
# `LicenseKey` is from your MaxMind account.
LicenseKey 4s1fax_4usdfassdsafdsakjukfdQROnc_sav
# `EditionIDs` is from your MaxMind account.
EditionIDs GeoLite2-ASN GeoLite2-City GeoLite2-CountrySave this conf file to ~/GeoIP.conf on your server.
Log in your server as root.
1
2
3
4sudo add-apt-repository ppa:maxmind/ppa
sudo apt update
sudo apt install geoipupdate
geoipupdate -f GeoIP.confThen there should be three geo-ip database downloaded in /usr/share/GeoIP
GeoLite2-ASN.mmdb GeoLite2-City.mmdb GeoLite2-Country.mmdb
Configure nginx redirection
Log in your server as root
1 | vim /etc/nginx/conf.d/99_geoip2_global.conf |
1 | # --- Free country database --- |
1 | vim /etc/nginx/sites-available/example.com |
1 | # Redirect all HTTP traffic to HTTPS |