目錄
- Install
- Config
- 應用
Install
# U22
apt install libnginx-mod-http-geoip2
cd /etc/nginx/modules-enabled
ln -s /usr/share/nginx/modules-available/mod-http-geoip2.conf 50-mod-http-geoip2.conf
load_module modules/ngx_http_geoip2_module.so;
Config
nginx.conf
http { ... include conf.d/*.conf; include vhosts/*.conf; }
conf.d/geoip2.conf
# geoip2
geoip2 /usr/share/geoip/dbip-country-lite.mmdb {
auto_reload 5m;
$geoip2_data_country_code default=UNKNOWN country iso_code;
}
vhosts/vhost.conf
# vhosts
server {
location = / {
default_type 'text/html';
add_header expires "0";
add_header cache-control "no-store, private";
echo '<html><body><pre>';
echo $remote_addr;
echo $geoip2_data_country_code;
echo '</pre></body></html>';
}
location / { try_files $uri $uri/ =404; }
}
Syntax
$variable_name [default=<value>] [source=$variable_with_ip] 'data path'
- If default is not specified, the variable will be empty if not found.
- If source is not specified, $remote_addr will be used to perform the lookup.
- data path 是 mmdblookup 的 "data path" (e.g. "country iso_code")
e.g.
$geoip2_data_country_code default=UNKNOWN country iso_code;
Settings
Autoreload (default: disabled):
nginx check the modification time of the database at the specified interval and reload it if it has changed.
auto_reload <interval>
用 soft link 可以方便 reload
cd /usr/share/geoip
ln -s dbip-country-lite-2024-09.mmdb dbip-country-lite.mmdb
應用
限制國家訪問
snippets/allowed_country.conf
# geoip2 map map $geoip2_data_country_code $allowed_country { default no; #HK yes; CN yes; }
nginx.conf
http { # Get Var $allowed_country include snippets/allowed_country.conf; ... }
sites-enabled/vhosts.conf
server { # FIRST on server # 用於跳過 country checking if ($allow_ip) { break; } if ($allowed_country = no) { return 400; } ... }
Notes
用 400 比 403 好, 這樣易於 debug