nginx配置攔截指定國家IP

Cookie_1030發表於2017-11-08

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


[root@localhost opt]# tar zxvf GeoIP.tar.gz

[root@localhost opt]# cd GeoIP-1.4.8

[root@localhost opt]# ./configure

[root@localhost opt]# make && make install


[root@localhost opt]# gunzip GeoIP.dat.gz

[root@localhost opt]# gunzip GeoLiteCity.dat.gz 


[root@localhost opt]# mv GeoIP.dat /opt/nginx/geoip/

[root@localhost opt]# mv GeoLiteCity.dat /opt/nginx/geoip/



[root@localhost opt]# cat /opt/nginx/conf/nginx.conf

user  www;
worker_processes  3;


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




events {
    worker_connections  1024;
}




http {
    include       /opt/nginx/conf/mime.types;
    default_type  application/octet-stream;
    include       /opt/nginx/sites-enabled/*;
    geoip_country  /opt/nginx/geoip/GeoIP.dat;
    geoip_city     /opt/nginx/geoip/GeoLiteCity.dat;



    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;


    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header X-Forwarded-Host $server_name;
    proxy_set_header X-Real-IP  $remote_addr;


    sendfile        on;
    #tcp_nopush     on;


    keepalive_timeout  300;


    charset utf-8;
    gzip  on;
    server_tokens off;


    fastcgi_connect_timeout 300s;
    fastcgi_send_timeout 300s;
    fastcgi_read_timeout 300s;
    fastcgi_buffer_size 128k;
    fastcgi_buffers 8 128k;
    fastcgi_busy_buffers_size 128k;
    fastcgi_temp_file_write_size 256k;
    fastcgi_intercept_errors on;
    
    include /opt/nginx/conf.d/*.conf;
}


[root@localhost opt]# cat /opt/nginx/conf.d/www.cookie.com.conf

server {
    listen       443;
    server_name  www.cookie.com;


    if ($geoip_country_code = HK) {
                return 404;
                }

……

……

……

}

重啟nginx即可


相關文章