一直想把网站主动屏蔽大陆 IP,想得很复杂所以一直没弄,今天试着搞一下发现超简单。

Nginx 官方 Ubuntu 仓库里可以直接 apt install nginx-module-geoip,然后手动在 nginx.conf 里加 load_module modules/ngx_http_geoip_module.so; 以及 http { 段加 geoip_country /usr/share/GeoIP/GeoIP.dat;,最后 nginx 里配

error_page 451 /error-cn.html;

location / {
	if ( $geoip_country_code = CN ) {
		return 451;
	}

但有个小细节卡了我 20 分钟才搞明白,因为 /error-cn.html/ 管,没法访问,所以只有错误码而显示不出 html 页(正文长度 0),所以 location / 之前需要再加一个

location = /error-cn.html {
	internal;
}