Skip to content

在spring boot项目和nginx结合时获取真实IP

GeXiangDong edited this page Jan 21, 2023 · 6 revisions

设置NGINX,把真实IP转发过来

location / {
    proxy_pass http://127.0.0.1:8008/;
    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_set_header X-Forwarded-Proto   $scheme;
    proxy_redirect                                         off;
}

配置spring boot中内嵌的tomcat,使用header中的IP

修改application.yml

spring boot 2.3 及以后

server:
  forward-headers-strategy: NATIVE
  tomcat:
    remoteip:
      remote-ip-header: X-Real-IP
      protocol-header: X-Forwarded-Proto

2.3之前版本

server:
  tomcat:
    remote-ip-header: X-Real-IP
    protocol-header: X-Forwarded-Proto

之后在程序中获取的IP就是真实的IP地址了。

配置文件参考文档 https://docs.spring.io/spring-boot/docs/2.7.0/reference/html/application-properties.html#application-properties.server.server.tomcat.remoteip.remote-ip-header