在 nginx.conf 中:
http {
geoip_country /etc/nginx/GeoIP.dat;
...
}
如果我做:
server{
...
location / {
add_header X-Geo $geoip_country_code;
add_header X-Geo3 $geoip_country_code3;
add_header X-IP $remote_addr;
...
}
}
仅X-IP
显示在我的标题中。
$ curl -I www.example.org
HTTP/1.1 302 FOUND
Content-Type: text/html; charset=utf-8
Date: Thu, 17 Jan 2013 19:29:23 GMT
Location: http://www.example.org/login/?next=/
Server: nginx/1.2.2
Vary: Cookie
X-IP: 10.139.34.12
Connection: keep-alive
如果我将位置块更改为:
location / {
add_header X-Geo "foo";
add_header X-Geo3 "bar";
add_header X-IP $remote_addr;
...
}
标题出现了,我该如何获取$geoip_country_code
?
答案1
我刚刚发现 geo_ip 有一个内部选项可以使用X-Forwarded-For
:
syntax: geoip_proxy address | CIDR;
default: —
context: http
This directive appeared in versions 1.3.0 and 1.2.1.
Defines trusted addresses. When a request comes from a trusted address, an address from the “X-Forwarded-For” request header field will be used instead.
答案2
啊,我刚刚才搞清楚发生了什么。它试图解析 LoadBalancers IP 而不是客户端的 GeoIP,这就是它空白的原因。一旦我直接 curl 主机,它就会返回正确的结果。我必须使用 HttpRealipModule 为 HttpGeoipModule 提供客户端 IP。在我的配置中:
real_ip_header X-Forwarded-For;
set_real_ip_from 0.0.0.0/0;
答案3
当您访问 / URL 时,如何确认正在发送哪些标头?您可以尝试这个 curl 命令吗?
与此类似,但带有您的 URL:
% curl -I www.google.com
HTTP/1.1 200 OK
Date: Thu, 17 Jan 2013 18:58:36 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Type: text/html; charset=ISO-8859-1
Set-Cookie: PREF=ID=39403a60450f4bb3:FF=0:TM=1358449116:LM=1358449116:S=uoBAz3VFZpjyc1hA; expires=Sat, 17-Jan-2015 18:58:36 GMT; path=/; domain=.google.com
Set-Cookie: NID=67=MBsS_mn5gvM2Zzt6Q6kfIO5h_brntWLnAmxZAXsNPseUgb5puv_8p8Io0ybgRqY62z0ihF-G5DLFtQOMN5MyIzM70IgPbkN4qOXKhCnQuUUqGCyuKkCg5XL6WfZoDR9m; expires=Fri, 19-Jul-2013 18:58:36 GMT; path=/; domain=.google.com; HttpOnly
P3P: CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info."
Server: gws
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Transfer-Encoding: chunked
答案4
或者,您可以在配置时指定您的 IP 源地理信息阻止。注意:我只在 GeoIP2 上测试过此功能
geoip2 /etc/nginx/GeoIP/GeoLite2-Country.mmdb {
$geoip2_data_country_code source=$http_x_forwarded_for country iso_code;
}