nginx反向代理后端web服务器记录客户端ip地址

nginx在做反向代理的时候,后端的nginx web服务器log中记录的地址都是反向代理服务器的地址,无法查看客户端访问的真实ip。

在反向代理服务器的nginx.conf配置文件中进行配置。

 location /bbs {
            proxy_pass http://192.168.214.131/bbs;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

}

在后端的nginx web服务器上,要确认nginx有没有编译安装 --with-http_realip_module模块。

 realip 模块的作用是:当本机的nginx处于一个反向代理的后端时获取到真实的用户IP。

如果没有realip模块,nginx的access_log里记录的IP会是反向代理服务器的IP,PHP中$_SERVER[‘REMOTE_ADDR’]的值也是反向代理的IP。

而安装了realip模块,并且配置正确,就可以让nginx日志和php的REMOTE_ADDR都变成真实的用户IP。

如果后端nginx没有安装realip模块,可以在线平滑添加新模块

nginx添加realip模块,(这里是后端web服务器)
先查看已经编译过的模块 /usr/local/webserver/nginx/sbin/nginx -V

    1、cd nginx-1.8.0
    2 、/configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_stub_status_module --with-pcre=/mnt/lnmp/pcre-8.31 --with-http_realip_module    3、           3、make     --不要make install 否则会覆盖以前的配置文件

    4 、 cp /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.bak

    5、 cp objs/nginx       /usr/local/nginx/sbin/       #如果出现  “nginx正在忙的提示”  先停止nginx运行
    6、 /usr/local/nginx/sbin/nginx -V
    7、 /usr/local/nginx/sbin/nginx

  

然后在后端nginx web服务器的nginx.conf配置文件中进行修改。

          proxy_set_header Host $host;
          proxy_set_header X-Real-IP $remote_addr;
          set_real_ip_from 192.168.214.132;          #set_real_ip_from指令是告诉nginx 192.168.214.132是我们的反代服务器,不是真实的用户IP real_ip_header X-Real-IP; #real_ip_header则是告诉nginx真正的用户IP是存在X-Forwarded-For请求头中
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;


同时启用web服务器的日志记录,使用默认即可。

http {
    include       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  logs/access.log  main;

....

  

ngx_http_realip_module使用详解

https://leo108.com/pid-2132/

- - -欢迎访问个人博客:gudaoyufu.com - - -
原文地址:https://www.cnblogs.com/anay/p/7788115.html