nginx代理模式下java获取客户端真实ip地址

张开发
2026/4/3 12:29:03 15 分钟阅读
nginx代理模式下java获取客户端真实ip地址
文章目录一、简要概述二、Java代码三、功能验证1. 编排文件2. 代理配置3. nginx配置4. 功能验证5. 源码放送一、简要概述获取客户端ip地址是开发中常见的功能需求获取ip地址后一般可以记录日志备查或者针对ip做访问控制。nginx代理模式下如何获取客户端真实ip地址呢二、Java代码为了简单起见我们封装了restful接口用来直接返回ip核心代码如下importjavax.servlet.http.HttpServletRequest;importorg.apache.commons.lang3.StringUtils;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RestController;importlombok.extern.slf4j.Slf4j;Slf4jRestControllerpublicclassIndexController{AutowiredHttpServletRequestrequest;GetMapping({/,/index})publicStringindex(){returnStringUtils.join(client ip: ,getClientIp());}String[]IP_HEADERS{X-Forwarded-For,X-Real-IP,Proxy-Client-IP,WL-Proxy-Client-IP,HTTP_X_FORWARDED_FOR,HTTP_X_FORWARDED,HTTP_X_CLUSTER_CLIENT_IP,HTTP_CLIENT_IP,HTTP_FORWARDED_FOR,HTTP_FORWARDED,HTTP_VIA,REMOTE_ADDR};/** * 获取客户端真实IP地址 */privateStringgetClientIp(){for(Stringheader:IP_HEADERS){Stringiprequest.getHeader(header);if(ip!null!ip.isEmpty()!unknown.equalsIgnoreCase(ip)){// 处理多个IP的情况逗号分隔log.info(##### ip header: {},header);String[]ipsip.split(,);returnips[0].trim();}}log.info(##### request.getRemoteAddr);returnrequest.getRemoteAddr();}}为了方便运行已经将工程打包成docker镜像地址为registry.cn-shanghai.aliyuncs.com/00fly/springboot-nginx:1.0.0三、功能验证目录结构├── conf.d │ └── web.conf ├── docker-compose.yml1. 编排文件docker-compose.ymlservices:nginx:image:nginx:alpinecontainer_name:my-nginxdeploy:resources:limits:cpus:2.0memory:10Mreservations:cpus:2.0memory:10Mports:-8080:80links:-web:webrestart:on-failurevolumes:-./conf.d/:/etc/nginx/conf.d/logging:driver:json-fileoptions:max-size:5mmax-file:1web:hostname:webimage:registry.cn-shanghai.aliyuncs.com/00fly/springboot-nginx:1.0.0container_name:webdeploy:resources:limits:cpus:2.0memory:200Mreservations:cpus:2.0memory:200Menvironment:CONTEXT_PATH:/#CONTEXT_PATH: /luckrestart:on-failurelogging:driver:json-fileoptions:max-size:5mmax-file:12. 代理配置web.confserver{listen80;proxy_set_header Host$host;proxy_set_header X-Real-IP$remote_addr;proxy_set_header X-Forwarded-For$proxy_add_x_forwarded_for;location /{proxy_pass http://web:8080;client_max_body_size 5m;}error_page500502503504/50x.html;location/50x.html{root /usr/share/nginx/html;}}3. nginx配置首先确保启用了realip模块进入nginx容器内执行nginx -V 查看返回是否有--with-http_realip_module如有说明当前版本镜像已经启用了realip模块。[root00fly docker]# docker psCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES ef8e4b3d8269 nginx:alpine/docker-entrypoint.…5seconds ago Up3seconds0.0.0.0:8080-80/tcp, :::8080-80/tcp my-nginx 5830a2be7439 registry.cn-shanghai.aliyuncs.com/00fly/springboot-nginx:1.0.0java -Djava.securit…5seconds ago Up4seconds8080/tcp web[root00fly docker]# docker exec -it my-nginx shnginx-Vnginx version: nginx/1.29.7 built by gcc15.2.0(Alpine15.2.0)built with OpenSSL3.5.527Jan2026TLS SNI support enabled configure arguments:--prefix/etc/nginx --sbin-path/usr/sbin/nginx --modules-path/usr/lib/nginx/modules --conf-path/etc/nginx/nginx.conf --error-log-path/var/log/nginx/error.log --http-log-path/var/log/nginx/access.log --pid-path/run/nginx.pid --lock-path/run/nginx.lock --http-client-body-temp-path/var/cache/nginx/client_temp --http-proxy-temp-path/var/cache/nginx/proxy_temp --http-fastcgi-temp-path/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path/var/cache/nginx/uwsgi_temp --http-scgi-temp-path/var/cache/nginx/scgi_temp --with-perl_modules_path/usr/lib/perl5/vendor_perl--usernginx--groupnginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-http_v3_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt-Os -fstack-clash-protection -Wformat -Werrorformat-security -fno-plt -g--with-ld-opt-Wl,--as-needed,-O1,--sort-common -Wl,-z,pack-relative-relocs其次查看代理配置是否包含下面的配置proxy_set_header Host$host;proxy_set_header X-Real-IP$remote_addr;proxy_set_header X-Forwarded-For$proxy_add_x_forwarded_for;4. 功能验证使用下面的脚本启动容器docker-compose--compatibilityup-d访问首页 http:{ip}:8080查看返回值 如 client ip: 122.51.4.65将此返回值与本地ip查询网址值对比。5. 源码放送http://118.178.86.130:8081/git/down?namespringboot-nginx有任何问题和建议都可以向我提问讨论,大家一起进步谢谢!-over-

更多文章