geo指令使用ngx_http_geo_module模块提供的。默认情况下,nginx有加载这个模块,除非人为的 –without-http_geo_module。
ngx_http_geo_module模块可以用来创建变量,其值依赖于客户端IP地址。
语法: geo [$address] $variable { … }
默认值: —
配置段: http
定义从指定的变量获取客户端的IP地址。默认情况下,nginx从$remote_addr变量取得客户端IP地址,但也可以从其他变量获得。如
geo $remote_addr $geo {
default 0;
127.0.0.1 1;
}
geo $arg_ttlsa_com $geo {
default 0;
127.0.0.1 1;
}
如果该变量的值不能代表一个合法的IP地址,那么nginx将使用地址“255.255.255.255”。
nginx通过CIDR或者地址段来描述地址,支持下面几个参数:
– delete:删除指定的网络
– default:如果客户端地址不能匹配任意一个定义的地址,nginx将使用此值。 如果使用CIDR,可以用“0.0.0.0/0”代替default。
– include: 包含一个定义地址和值的文件,可以包含多个。
– proxy:定义可信地址。 如果请求来自可信地址,nginx将使用其“X-Forwarded-For”头来获得地址。 相对于普通地址,可信地址是顺序检测的。
– proxy_recursive:开启递归查找地址。 如果关闭递归查找,在客户端地址与某个可信地址匹配时,nginx将使用“X-Forwarded-For”中的最后一个地址来代替原始客户端地址。如果开启递归查找,在客户端地址与某个可信地址匹配时,nginx将使用“X-Forwarded-For”中最后一个与所有可信地址都不匹配的地址来代替原始客户端地址。
– ranges:使用以地址段的形式定义地址,这个参数必须放在首位。为了加速装载地址库,地址应按升序定义。
geo $country {
default ZZ;
include conf/geo.conf;
delete 127.0.0.0/16;
proxy 192.168.100.0/24;
proxy 2001:0db8::/32;
127.0.0.0/24 US;
127.0.0.1/32 RU;
10.1.0.0/16 RU;
192.168.1.0/24 UK;
}
vim conf/geo.conf
10.2.0.0/16 RU;
192.168.2.0/24 RU;
地址段例子:
geo $country {
ranges;
default ZZ;
127.0.0.0-127.0.0.0 US;
127.0.0.1-127.0.0.1 RU;
127.0.0.1-127.0.0.255 US;
10.1.0.0-10.1.255.255 RU;
192.168.1.0-192.168.1.255 UK;
}
[warning]遵循最精确匹配原则,即nginx使用能最精确匹配客户端地址的值。[/warning]
上面的例子几乎都是官网说明例子。下面举例说明便于理解该指令的用法。
http {
#geo $remote_addr $ttlsa_com {
geo $ttlsa_com {
default 0;
127.0.0.1 1;
}
server {
listen 8080;
server_name test.ttlsa.com;
location /hello {
default_type text/plain;
echo $ttlsa_com;
echo $arg_boy;
}
}
}
# curl 127.0.0.1:8080/hello?boy=默北
1
默北
http {
geo $arg_boy $ttlsa_com {
default 0;
127.0.0.1 1;
8.8.8.8 2;
}
server {
listen 8080;
server_name test.ttlsa.com;
location /hello {
default_type text/plain;
echo $ttlsa_com;
echo $arg_boy;
}
}
}
# curl 127.0.0.1:8080/hello?boy=8.8.8.8
2
8.8.8.8
http {
geo $arg_boy $ttlsa_com {
default 0;
127.0.0.1/24 24;
127.0.0.1/32 32;
8.8.8.8 2;
}
server {
listen 8080;
server_name test.ttlsa.com;
location /hello {
default_type text/plain;
echo $ttlsa_com;
echo $arg_boy;
}
}
}
# curl 127.0.0.1:8080/hello?boy=127.0.0.1
32
127.0.0.1
# curl 127.0.0.1:8080/hello?boy=127.0.0.12
24
127.0.0.12
geo指令主要是根据IP来对变量进行赋值的。因此geo块下只能定义IP或网络段,否则会报错“nginx: [emerg] invalid network”。