nginx获取真实ip

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了nginx获取真实ip相关的知识,希望对你有一定的参考价值。

参考技术A 通过nginx获取用户真实IP

nginx配置

location /

    proxy_set_header            Host $host;

    proxy_set_header            X-real-ip $remote_addr;

    proxy_set_header            X-Forwarded-For $proxy_add_x_forwarded_for;



如上面配置,接口需要使用的时候获取X-real-ip就可以,但是经过测试以后,发现X-real-ip并不是真实的用户IP,而是Nginx代理服务器的IP,原因就是经过多级代理,$remote_addr是上一级的IP。

名词解释

$remote_addr

获取到上一级代理的IP

proxy_add_x_forwarded_for

获取到结果例如:(223.104.6.125, 10.10.10.45),第一个是用户的真实IP,第二个是一级代理的IP,依此类

通过上面的分析我们可以从proxy_add_x_forwarded_for中获取到用户的真实IP,使用正则匹配获取第一个即可,如下:

location /

    proxy_set_header            Host $host;

    set $Real $proxy_add_x_forwarded_for;

    if( $Real ~ (\d+)\.(\d+)\.(\d+)\.(\d+),(.*) )

        set$Real $1.$2.$3.$4;

   

    proxy_set_header            X-real-ip $Real;

    proxy_set_header            X-Forwarded-For $proxy_add_x_forwarded_for;



也可以通过后台的程序,从请求的header里获取X-Forwarded-For,然后取起一个值即可

文章来自: https://www.cnblogs.com/jin-zhe/p/11989012.html

百度云BLB后NGINXTOMCAT获取真实IP

百度云BLB后NGINX、TOMCAT获取真实IP


一、BLB后Nginx如何获取真实IP

前提:nginx作为slb获取真实ip是使用 http_realip_module,默认一键安装包安装的nginx没有安装这个模块需要重新重新编译nginx并加装。

查看是否安装此模块:./nginx -V

如没有安装此模块,需重新编译nginx增加 --with-http_realip_module

1、百度云BLB需要开启获取真实IP(默认已开启)

2、修改Nginx配置文件nginx.conf

添加:

http {

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '               '$status $body_bytes_sent "$http_referer" '               '"$http_user_agent" "$http_x_forwarded_for"';

access_log  /home/logs/nginx_access.log  main;

server {     listen 80;     server_name domain_name;     location / {       proxy_set_header Host $http_host;       proxy_redirect off;       proxy_set_header X-Real-IP $remote_addr;       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;       proxy_pass http://IPADDR:PORT;     }  }

3、日志内容如下:

技术分享图片

二、BLB后Tomcat如何获取真实IP

1、修改Tomcat配置文件

技术分享图片

2、重启Tomcat服务,日志内容如下:

技术分享图片


以上是关于nginx获取真实ip的主要内容,如果未能解决你的问题,请参考以下文章

获取用户真实IP:(模拟:客户端--F5--nginx--tomcat 后端获取用户真实IP)

nginx如何获取自己的ip

前端Nginx,后端Apache获取用户真实IP地址

图解 nginx 如何获取真实的来源 IP

Nginx获取反向代理真实IP和向下转发

百度云BLB后NGINXTOMCAT获取真实IP