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

时间:2016-04-01 12:40:27

标签: spring tomcat nginx spring-boot http-headers

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

  1. X-Real-IP标头是否用于获取真实的客户端IP?
  2. tomcat使用此标头在访问日志中写入IP地址吗?
  3. 我有这个配置:

    application.properties

    server.use-forward-headers=true
    server.tomcat.internal-proxies=127\\.0\\.0\\.1
    server.tomcat.accesslog.enabled=true
    

    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;
    }
    

1 个答案:

答案 0 :(得分:4)

真实客户端IP位于$proxy_add_x_forwarded_for变量,即X-Forwarded-For标头中。它会有","分开的条目。第一个值是真实的客户端IP。

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

%{X-Forwarded-For}i %l %u %t "%r" %s %b