nginx反向代理实现获取用户真实ip

参考资料:https://www.cnblogs.com/mzhaox/p/11214747.html

用户真实ip是223.193.x.x,发送请求,请求经过Nginx A->Nginx B -> 最后到达后端服务
nginx A的关键配置:

复制代码
http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    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  /var/log/nginx/access.log  main;

    sendfile        on;

    keepalive_timeout  65;
    client_max_body_size 10000m;


    server {
        listen  6794;

        root /mnt/dist;
        location /myapi/ {
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_pass  http://xxx.xxx.xxx:xxx;  # nginx B的地址

         }
复制代码

nginx B的关键配置:

复制代码
http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

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

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;
    # gzip
    include /etc/nginx/conf.ext/*.conf;

    client_max_body_size 1g;

    server {
        listen  5111;

        set_real_ip_from yyy.yyy.yyy.yyy;  # NGINX A的IP 。如果nginx B前面有多个nginx,可以把多个nginx的IP都写上
        real_ip_header X-Forwarded-For;
        real_ip_recursive on;

        root /mnt/dist;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
复制代码

1.使用realip模块后,$remote_addr输出结果为真实客户端IP,可以使用$realip_remote_addr获取最后一个反向代理的IP;
          2.real_ip_headerX-Forwarded-For:告知Nginx真实客户端IP从哪个请求头获取;
          3.set_real_ip_from 172.25.78.0/24:告知Nginx哪些是反向代理IP,即排除后剩下的就是真实客户端IP
          4.real_ip_recursive on:是否递归解析,当real_ip_recursive配置为off时,Nginx会把real_ip_header指定的请求头中的最后一个IP作为真实客户端IP;
          当real_ip_recursive配置为on时,Nginx会递归解析real_ip_header指定的请求头,最后一个不匹配set_real_ip_from的IP作为真实客户端IP。 

 

posted on   我和你并没有不同  阅读(121)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示