http {
# 定义允许访问的IP列表
geo $allowed_ip {
default 0;
192.168.1.0/24 1;
10.0.0.1 1;
}
server {
listen 80;
location / {
if ($allowed_ip = 0) {
return 403;
}
proxy_pass http://backend;
}
}
}
location /admin {
allow 192.168.1.100;
allow 10.0.0.0/8;
deny all;
proxy_pass http://backend;
}
http {
map $remote_addr $ip_acl {
default "deny";
"192.168.1.1" "allow";
"10.0.0.0/8" "allow";
}
server {
listen 80;
location / {
if ($ip_acl = "deny") {
return 403;
}
proxy_pass http://backend;
}
}
}
首先需要确保Nginx编译时包含了--with-http_geoip_module
选项,并安装GeoIP数据库。
http {
geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $allowed_country {
default no;
US yes;
CA yes;
GB yes;
}
server {
listen 80;
location / {
if ($allowed_country = no) {
return 403;
}
proxy_pass http://backend;
}
}
}
http {
geoip2 /usr/share/GeoIP/GeoLite2-Country.mmdb {
$geoip2_data_country_code country iso_code;
}
map $geoip2_data_country_code $allowed_country {
default no;
US yes;
CA yes;
GB yes;
}
server {
listen 80;
location / {
if ($allowed_country = no) {
return 403;
}
proxy_pass http://backend;
}
}
}
http {
geoip2 /usr/share/GeoIP/GeoLite2-Country.mmdb {
$geoip2_data_country_code country iso_code;
$geoip2_data_continent_code continent code;
}
map "$geoip2_data_continent_code:$geoip2_data_country_code" $region_acl {
default "deny";
"EU:DE" "allow";
"NA:US" "allow";
"AS:JP" "allow";
}
server {
listen 80;
location / {
if ($region_acl = "deny") {
return 403 "Access denied for your region";
}
proxy_pass http://backend;
}
}
}
http {
# IP ACL
geo $allowed_ip {
default 0;
192.168.1.0/24 1;
}
# GeoIP ACL
geoip2 /usr/share/GeoIP/GeoLite2-Country.mmdb {
$geoip2_data_country_code country iso_code;
}
map $geoip2_data_country_code $allowed_country {
default 0;
US 1;
CA 1;
}
server {
listen 80;
location / {
# 允许内部IP或来自允许国家的访问
if ($allowed_ip = 0) {
if ($allowed_country = 0) {
return 403;
}
}
proxy_pass http://backend;
}
}
}
通过以上配置,您可以灵活地控制Nginx反向代理的访问权限,基于IP地址或地理位置来允许或拒绝请求。