nginx-realip问题解决方案
- 一、配置真实ip解析
- 二、日志中记录真实 IP
- 三、在日志中验证
一、配置真实ip解析
让backend server知道前端是谁来访问的,知道他们的ip地址
LB在转发数据包的时候,在http请求报文里增加一个字段,携带user的ip地址,这样backend server就知道user的ip地址了
在负载均衡器上修改http请求报文头部字段,添加一个X-Real-IP字段
配置在监听80端口的server 虚拟主机上,到时访问的时候使用http协议访问
[root@LB conf]# vim nginx.confserver {listen 80;location / {# 转发给负载均衡器proxy_pass http://myweb1;proxy_set_header X-Real-IP $remote_addr;}[root@LB conf]# nginx -t
nginx: the configuration file /usr/local/nginx1/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx1/conf/nginx.conf test is successful
[root@LB conf]# nginx -s reload
将nginx内部的remote_addr这个变量的值,赋值给X-Real-IP这个变量,X-Real-IP这个变量会在http协议的请求报文里添加一个X-Real-IP的字段,后端的real server 服务器上的nginx就可以读取这个字段的值 X-Real-IP
这个变量名可以自己定义,随便取名,后面引用的时候,不区分大小写
二、日志中记录真实 IP
在后端real server上使用这个x_real_ip这个字段
web1和web2服务器上都要进行修改
[root@web-1 conf]# vim nginx.conf
http {include mime.types;include /usr/local/nginx1/conf/conf.d/*.conf;server_tokens off;#在日志文件的格式里,增加变量$http_x_real_ip 表示我们引用这个变量的值写到日志文件里log_format main '$http_x_real_ip - $remote_addr - $remote_user [$time_local] "$request" ''$status $body_bytes_sent "$http_referer" ''"$http_user_agent" "$http_x_forwarded_for"';#启用下main格式的访问日志access_log logs/access.log main;server {listen 80;server_name www.huang.com;access_log logs/huang.com.access.log main;
.......省略[root@web-1 conf]# nginx -t
nginx: the configuration file /usr/local/nginx1/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx1/conf/nginx.conf test is successful
[root@web-1 conf]# nginx -s reload
三、在日志中验证
测试 -> 访问LB
效果就是在日志文件里能看到前端用户的ip地址,具体看哪个日志文件,需要在web服务器上确认访问的是哪个虚拟主机,然后确认是哪个access.log文件,就能看到real ip的地址
[root@web2 logs]# tail -f huang.com.access.log
配置在监听443端口的server 虚拟主机里,访问的时候使用https协议