一、nginx后端負載服務器的API在獲取客戶端IP時始終只能獲取nginx的代理服務器IP,排查nginx配置如下
upstream sms-resp { server 192.168.5.216:8501; server 192.168.5.217:8501; } server { listen 80; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; location / { #root html; #index index.html index.htm; proxy_pass http://sms-resp; 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配置項已經配置了轉換真實客戶端IP的參數設置,那么需要抓包來看看是否是真正的轉換了客戶端IP。
二、安裝tcpdump抓包工具
在nginx和后端API服務器上分別安裝tcpdump
[root@push-5-216 ~]# yum install -y tcpdump
三、使用tcpdump抓包
在172.28.146.109上瀏覽器調用172.28.5.215的nginx代理的HTTP接口,nginx將請求分發到172.28.5.216上,這里nginx和后端API均配置雙網卡(172.28.5.215\182.168.5.215\172.28.5.216\192.168.5.216),他們之間走的192.168網段。
在172.28.5.215的80端口上抓取從172.28.146.109過來的TCP包,同時nginx會將請求轉發到192.168.5.216的8501端口上,同時也在172.28.5.216的8501端口上上抓取從192.168.5.215上過來的tcp包
在172.28.5.215上執行
[root@push-5-215 ~]# tcpdump -i em1 tcp port 80 and host 172.28.146.109 -c 100 -n -vvv -w /opt/nginx-215.cap tcpdump: listening on em1, link-type EN10MB (Ethernet), capture size 262144 bytes Got 0
-i:監聽哪個網卡
tcp:監聽哪個協議包(tcp\udp\ssh\)
port:監聽端口
and host:監聽指定IP地址進入的數據包(入)
dst host :監聽發給指定IP地址的數據包(出)
-c:監聽多少個數據包
-n:顯示IP地址
-vvv:顯示詳細信息
-w:將監聽信息輸出到文件
在172.28.5.216上執行
[root@push-5-216 ~]# tcpdump -i em2 port 8501 and host 192.168.5.215 -c 100 -n -vvv -w /opt/nginx-216.cap tcpdump: listening on em2, link-type EN10MB (Ethernet), capture size 262144 bytes Got 0
然后在172.28.146.109上調用測試接口:http://172.28.5.215/sms-report?xxxxxxx=xxxxxx&xxx=xxxxxxx, 此時,在抓包的兩台服務器上均顯示有數據包捕獲
[root@push-5-215 ~]# tcpdump -i em1 tcp port 80 and host 172.28.146.109 -c 100 -n -vvv -w /opt/nginx-215.cap tcpdump: listening on em1, link-type EN10MB (Ethernet), capture size 262144 bytes Got 22
[root@push-5-216 ~]# tcpdump -i em2 port 8501 and host 192.168.5.215 -c 100 -n -vvv -w /opt/nginx-216.cap tcpdump: listening on em2, link-type EN10MB (Ethernet), capture size 262144 bytes Got 10
此時按ctrl+c中斷監聽,sz下載nginx-215.cap和nginx-216.cap文件到本地
四、利用wireshark工具分析數據包日志文件
打開nginx-215.cap
顯示調用接口的數據包
再打開nginx-216.cap
這條數據包即為nginx轉發到216的請求數據,雙擊打開詳細信息窗口
在data字段里可以看到轉發的請求數據,在下面的詳細信息中開始部分即為http請求頭,可以看到里面有X-real-ip和X-forwarded-for兩個字段這是在nginx配置文件里配置的參數,里面存放客戶端調用真實IP,顯示為172.28.146.109即為真實調用http接口的客戶端IP。