nginx作为反向代理,后端tomcat服务器获取真实客户端IP
如果要记录真实的客户端访问地址,需要进行如下配置:
1、反向代理服务器nginx.conf配置
在server后面增加三个参数用与记录IP:
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
案例:
server {
listen 80;
server_name 10.10.32.29;
upstream tomcat {
ip_hash;
server 10.10.32.29:8080 max_fails=1 fail_timeout=10s weight=1;
server 10.10.32.30:8080 max_fails=1 fail_timeout=10s weight=1;
}
location / {
proxy_pass http://tomcat;
proxy_redirect default;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr; #保留代理之前的真实客户端ip
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #记录代理过程
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
2、修改tomcat的配置文件
在server.xml中修改
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
prefix="localhost_access_log" suffix=".txt"
pattern="%{X-FORWARDED-FOR}i %h %l %u %t "%r" %s %b" />