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協議