需求

通过IP区别国内或国外,从而跳转到不同的页面,最终用nginx的第三方module:geoip来实现,这就不说它的优势了,网上很多解释,下面看怎么配置

模块

直接用yum来安装了geoip模块

yum install nginx-module-geoip

geoip数据库

mkdir /etc/nginx/geoipdat
cd /etc/nginx/geoipdat

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

#解压
gunzip GeoIP.dat.gz
gunzip GeoLiteCity.dat.gz

Nginx主配置

首先在nginx.conf中加载geoip的库,配置如下:

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;

#加载modules下的配置文件
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections  1024;
}


http {
    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;
    tcp_nodelay         on;
    keepalive_timeout   65;
    client_max_body_size 20M;
    types_hash_max_size 2048;

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

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

其实主要加载的modules配置是mod-http-geoip.conf文件,里面配置的也就是以下两句模块加载的配置

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

yum 安装的 Nginx 这些都是已经默认配置好的

虚拟主机配置

#加载IP地址库文件
geoip_country /etc/nginx/geoipdat/GeoIP.dat;
geoip_city /etc/nginx/geoipdat/GeoLiteCity.dat;

server {
    listen       80;
    server_name  localhost;
    location / {
        root /var/nginx/html;
        
        #判断ip是否是中国地区,如果是则重写url地址
        if ($geoip_country_code = CN){
        rewrite (.*) /zh$1 break;
        }
    
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   /usr/share/nginx/html;
        }
    }
}
Last modification:May 25th, 2019 at 12:15 am