Nginx 限制地区访问
Nginx 地区访问限制配置指南
在本指南中,我们将介绍如何在 CentOS 7 环境下使用 Nginx 限制特定地区的访问。我们将详细说明所需的依赖项、库、数据库和模块的安装过程,以及如何配置 Nginx 以禁止非中国 IP 地址的访问。
1. 准备资料
1.1 依赖项
首先,安装必要的依赖项:
sudo yum install -y GeoIP-devel.x86_64 libmaxminddb
1.2 libmaxminddb 库
下载 libmaxminddb 库:
1.3 GeoIP 地址数据库
下载 GeoIP 地址数据库:
1.4 ngx_http_geoip2_module 模块
下载 Nginx 的 GeoIP2 模块:
2. 开始安装
2.1 编译 libmaxminddb 库
-
解压并进入目录:
tar -zxvf libmaxminddb-1.9.1.tar.gz cd libmaxminddb-1.9.1 -
编译并安装:
./configure make sudo make install -
更新动态链接库配置:
echo /usr/local/lib >> /etc/ld.so.conf.d/local.conf sudo ldconfig
2.2 编译 Nginx 添加 GeoIP2 模块
-
进入 Nginx 源码目录,编译并添加 GeoIP2 模块:
./configure [之前的参数] --add-module=/root/ngx_http_geoip2_module-master make -
替换现有的 Nginx 可执行文件:
sudo mv /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.old sudo cp objs/nginx /usr/local/nginx/sbin/
3. Nginx 配置示例
以下是一个配置示例,禁止非中国的外网 IP 地址访问:
3.1 nginx.conf 配置
http {
...
# 配置 GeoIP2 数据库
geoip2 /usr/local/nginx/conf/GeoLite2-Country.mmdb {
auto_reload 1000m; # 每 1000 毫秒自动重载
$geoip2_data_country_code country iso_code; # 获取国家代码
}
# 定义允许的国家
map $geoip2_data_country_code $allowed_country {
default no; # 默认不允许
CN yes; # 中国允许
}
# 允许局域网 IP 段访问
geo $allowed_ip {
default no; # 默认不允许
192.168.0.0/16 yes; # 允许局域网 IP
}
# 结合国家和 IP 段设置访问权限
map "$allowed_country:$allowed_ip" $access_allowed {
default no; # 默认不允许
"yes:no" yes; # 中国 IP 或局域网 IP 允许
"no:yes" yes; # 局域网 IP 允许
"yes:yes" yes; # 中国 IP 和局域网 IP 允许
}
server {
...
# 如果访问不被允许,返回 403 状态码
if ($access_allowed = no) {
return 403; # 返回403状态码
}
...
}
}
3.2 配置说明
- geoip2:配置 GeoIP2 数据库的路径和自动重载时间。
- map:根据国家代码和 IP 地址段设置访问权限。
- if ($access_allowed = no):检查访问是否被允许,若不被允许则返回 403。
4. 测试配置
完成配置后,请按照以下步骤进行测试:
-
重新加载 Nginx 配置:
sudo systemctl reload nginx -
访问网站:
使用不同的 IP 地址访问您的网站,检查是否按照预期返回 403 状态码。
-
查看日志:
检查 Nginx 的访问日志和错误日志,确认配置是否生效:
sudo tail -f /var/log/nginx/access.log sudo tail -f /var/log/nginx/error.log
完成
通过以上步骤,您已成功配置 Nginx 限制地区访问的功能。这将帮助您有效管理用户访问,提高网站的安全性。根据实际需求,您可以进一步调整允许的国家和 IP 地址段的设置。