目前,我正面临Nginx和playframework的问题.我已经在play应用程序前面将Nginx配置为反向代理.
当我尝试在Java中(在Play框架中)读取客户端ip时,有时我可以获得正确的ip,但是有时我会收到“ 0:0:0:0:0:0:0:0:1”,甚至会得到多个ip地址类似于“ 222.72.xxx.xxx,10.210.44.35、115.239.xxx.x”.
似乎有时它可以工作,但经常出错.
这是我的Nginx.conf配置:
http {
##
# Basic Settings
##
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# server_tokens off;
# server_names_hash_bucket_size 64;
# server_name_in_redirect off;
upstream webapp {
server localhost:9000;
server localhost:9002;
}
server {
listen 80;
listen [::]:80;
server_name myserver.com;
return 301 http://www.myserver.com$request_uri;
}
server {
listen 80;
listen [::]:80;
server_name www.myserver.com;
location /assets/ {
root /home/myuser/apps;
}
location /static/ {
expires 30d;
root /home/myuser/apps;
}
location / {
proxy_pass http://webapp;
}
location /apis/ {
proxy_pass http://localhost:9001;
}
}
...
}
这是我从Nginx的access.log中提取的一些日志,以及我的Java应用程序中的日志:
access.log:
115.239.xxx.x - - [20/Aug/2014:22:30:29 +0200] "GET /news/article/53f00d5efeb89844977b5477 HTTP/1.1" 499 0 "http://www.myserver.com/news/article/53f00d5efeb89844977b5477" "Mozilla/5.0 (iphone; U; cpu iPhone OS 4_3_5 like Mac OS X; en-US) AppleWebKit/533.17.9 (KHTML,like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5”
Java应用程序日志:
2014-08-20 22:30:29,621 INFO application - Activity - IP: 222.72.xxx.xxx,10.210.44.35,115.239.xxx.x,URL: /news/article/53f00d5efeb89844977b5477,UserAgent: Mozilla/5.0 (iphone; U; cpu iPhone OS 4_3_5 like Mac OS X; en-US) AppleWebKit/533.17.9 (KHTML,like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5
顺便说一句,服务器还支持IPV6,这就是为什么我在Nginx.conf中添加了IPv6支持的原因.
谁能帮我吗?
非常感谢!
干杯,
马丁
最佳答案
Play中有一个配置选项,用于控制是否信任Nginx发送的X-Forwarded-For标头.您需要添加
trustxforwarded=true
到您的application.conf.你做完了吗?
在文档中“高级代理设置”标题下:https://www.playframework.com/documentation/2.3.x/HTTPServer