In nginx use geoip as the method of region restriction

  • 2020-05-17 07:46:51
  • OfStack

The blog notes for work

Environment:

nginx version: nginx/1.14.0

centos version: centos7

The requirements are as follows:

By IP distinction between domestic or foreign, so as to jump to different pages, finally use nginx third side module: geoip to achieve, this does not say its advantages, a lot of online explanation, how to see the configuration below

nignx.repo is configured in my system, and I installed geoip module directly with yum instead of adding and reprogramming modules


yum install nginx-module-geoip

Download the geoip database file


cd /etc/nginx
mkdir geoipdat
cd geoipdat

 download 

wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz

 Unpack the 

gunzip GeoIP.dat.gz
gunzip GeoLiteCity.dat.gz

Configure nginx as required

First, load the geoip library in nginx.conf, and configure it as follows:


load_module "modules/ngx_http_geoip_module.so";
load_module "modules/ngx_stream_geoip_module.so";

user nginx;
worker_processes 1;

error_log /var/log/nginx/error.log warn;
pid    /var/run/nginx.pid;


events {
  worker_connections 1024;
}


http {
  include    /etc/nginx/mime.types;
  default_type application/octet-stream;

  log_format main '$remote_addr - $remote_user [$time_local] "$request" '
           '$status $body_bytes_sent "$http_referer" '
           '"$http_user_agent" "$http_x_forwarded_for"';

  access_log /var/log/nginx/access.log main;

  sendfile    on;
  #tcp_nopush   on;

  keepalive_timeout 65;

  #gzip on;

  include /etc/nginx/conf.d/*.conf;
}

Configure the virtual host as follows:


geoip_country /etc/nginx/geoipdat/GeoIP.dat;
geoip_city /etc/nginx/geoipdat/GeoLiteCity.dat;


server {
  listen    80;
  server_name localhost;
  location / {
 root /opt;
 if ($geoip_country_code = CN){
 rewrite (.*) /zh$1 break;
 }
    rewrite (.*) /en$1 break;
  }
    error_page  500 502 503 504 /50x.html;
  location = /50x.html {
    root  /usr/share/nginx/html;
  }

}

The opt directory is as follows


[root@VM_0_15_centos opt]# tree
.
|
 └ ─ ─  en
 │      └ ─ ─  index.html
 └ ─ ─  zh
   └ ─ ─  index.html

The above is just a simple configuration 1...


Related articles: