如何在使用 Nginx 作为反向代理的 Spring Boot 应用程序的嵌入式 Tomcat 访问日志上记录真实客户端 IP?

Edu*_*ero 1 spring tomcat nginx http-headers spring-boot

我在启用了 Tomcat 访问日志的 Spring Boot 1.3.3 应用程序前面安装了 Nginx,但日志记录始终写入代理 IP 地址 (127.0.0.1) 而不是真实的客户端 IP。

  1. X-Real-IP 头是否用于获取真实的客户端 IP?
  2. 这个头是tomcat用来在访问日志中写入IP地址的吗?

我有这个配置:

应用程序属性

server.use-forward-headers=true
server.tomcat.internal-proxies=127\\.0\\.0\\.1
server.tomcat.accesslog.enabled=true
Run Code Online (Sandbox Code Playgroud)

nginx配置:

location / {
    proxy_pass http://127.0.0.1:8091;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto https;
    proxy_set_header X-Forwarded-Port 443;
    proxy_set_header Host $host;
}
Run Code Online (Sandbox Code Playgroud)

小智 5

真实客户端 IP 可在$proxy_add_x_forwarded_for变量 ieX-Forwarded-For标头中获得。它将有“,”分隔的条目。第一个值是真实的客户端 IP。

要在 Tomcat 的访问日志中记录真实的客户端 IP,请将 AccessLog Valve 中的模式值修改为:

%{X-Forwarded-For}i %l %u %t "%r" %s %b
Run Code Online (Sandbox Code Playgroud)