nginx 如何获取真实的 IP

2018-09-18 13:47:05 +08:00
 testVmap

客户端请求 A 服务器,A 服务器转发到 B B 的 nginx 日志是 A 的内网 IP,如何获得客户端的请求 IP

172.16.16.16 - - [09/Jun/2018:22:34:33 +0800] "GET /sogood/info.php HTTP/1.0" 200 16 "-" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36"

4134 次点击
所在节点    问与答
10 条回复
whatever93
2018-09-18 13:54:40 +08:00
x-forward-for
throns
2018-09-18 13:59:22 +08:00
可以看看这个配置:![Snipaste_2018-09-18_13-58-25.png]( https://i.loli.net/2018/09/18/5ba09414b3d96.png)
testVmap
2018-09-18 14:02:57 +08:00
A 服务器转发配置
location ^~ /sogood {
proxy_pass http://172.16.0.7:81;
proxy_pass_header Server;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_set_header Cookie $http_cookie;
proxy_set_header Referer $http_refere;
proxy_set_header X-Forwarded-For
$proxy_add_x_forwarded_for;
#proxy_set_header X-Forwarded-For $remote_addr;
#proxy_set_header REMOTE-HOST $remote_addr;

}


B 服务器转发配置
location ~ \.php$ {
proxy_pass http://127.0.0.1;
proxy_pass_header Server;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_set_header Cookie $http_cookie;
proxy_set_header Referer $http_refere;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}



加了感觉还是没用
lshero
2018-09-18 14:06:41 +08:00
取 header 里的 X-Real-IP 啊
testVmap
2018-09-18 14:10:38 +08:00
@lshero 是要怎么配置,要修改 log_format 吗
testVmap
2018-09-18 14:11:10 +08:00
A 服务器的日志能正常获取到真实 IP
throns
2018-09-18 14:12:39 +08:00
lshero
2018-09-18 14:51:07 +08:00
@testVmap 如果是从日志获取的话。log_format 可以参考一下这个 http://blog.51cto.com/nicking/1431056。如果程序要取的话把所有的 header 里添加的 X-Forwarded-For 或者 X-Real-IP 都成
jtsai
2018-09-18 15:22:09 +08:00
A 服务把客户端的请求头转到 B 服务器

location / {
# HTTP header
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

proxy_pass (B 服务器地址)

}
testVmap
2018-09-18 15:51:35 +08:00
感谢大家,最后配置如下
服务器 A 的转发配置
location ^~ /namesg/ {
proxy_pass http://172.16.16.11;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
}

服务器 B 的 nginx.conf log 配置

log_format my_format '$http_x_real_ip -'
'$remote_addr- [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log logs/access.log my_format;


主要是 nginx 日志取消注释后还不能生效,需要改下日志名字

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/490426

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX