隨着nginx的迅速崛起,越來越多公司將apache更換成nginx. 同時也越來越多人使用nginx作為負載均衡, 並且代理前面可能還加上了CDN加速,但是隨之也遇到一個問題:nginx如何獲取用戶的真實IP地址.
實例環境:
- 用戶IP 120.22.11.11
- CDN前端 61.22.22.22
- CDN中轉 121.207.33.33
- 公司NGINX前端代理 192.168.50.121(外網121.207.231.22)
1、使用CDN自定義IP頭來獲取
假如說你的CDN廠商使用nginx,那么在nginx上將$remote_addr賦值給你指定的頭,方法如下:
proxy_set_header remote-user-ip $remote_addr;
后端PHP代碼getRemoteUserIP.php
<?php $ip = getenv("HTTP_REMOTE_USER_IP"); echo $ip; ?>
訪問getRemoteUserIP.php,結果如下:
120.22.11.11 //取到了真實的用戶IP,如果CDN能給定義這個頭的話,那這個方法最佳
2、通過HTTP_X_FORWARDED_FOR獲取IP地址
一般情況下CDN服務器都會傳送HTTP_X_FORWARDED_FOR頭,這是一個ip串,后端的真實服務器獲取HTTP_X_FORWARDED_FOR頭,截取字符串第一個不為unkown的IP作為用戶真實IP地址, 例如:
120.22.11.11,61.22.22.22,121.207.33.33,192.168.50.121(用戶IP,CDN前端IP,CDN中轉,公司NGINX代理)
getFor.php
<?php $ip = getenv("HTTP_X_FORWARDED_FOR"); echo $ip; ?>
訪問getFor.php結果如下:
120.22.11.11,61.22.22.22,121.207.33.33,192.168.50.121
如果你是php程序員,你獲取第一個不為unknow的ip地址,這邊就是120.22.11.11.
3.使用nginx自帶模塊realip獲取用戶IP地址
安裝nginx之時加上realip模塊,我的參數如下:
./configure --prefix=/usr/local/nginx-1.4.1 --with-http_realip_module
真實服務器nginx配置
server { listen 80; server_name www.ttlsa.com; access_log /data/logs/nginx/www.ttlsa.com.access.log main; index index.php index.html index.html; root /data/site/www.ttlsa.com; location / { root /data/site/www.ttlsa.com; } location = /getRealip.php { set_real_ip_from 192.168.50.0/24; set_real_ip_from 61.22.22.22; set_real_ip_from 121.207.33.33; set_real_ip_from 127.0.0.1; real_ip_header X-Forwarded-For; real_ip_recursive on; fastcgi_pass unix:/var/run/phpfpm.sock; fastcgi_index index.php; include fastcgi.conf; } }
getRealip.php內容
<?php $ip = $_SERVER['REMOTE_ADDR']; echo $ip; ?>
訪問www.ttlsa.com/getRealip.php,返回:
120.22.11.11
如果注釋 real_ip_recursive on或者 real_ip_recursive off
訪問www.ttlsa.com/getRealip.php,返回:
121.207.33.33
很不幸,獲取到了中繼的IP,real_ip_recursive的效果看明白了吧.
- set_real_ip_from:真實服務器上一級代理的IP地址或者IP段,可以寫多行
- real_ip_header:從哪個header頭檢索出要的IP地址
- real_ip_recursive:遞歸排除IP地址,ip串從右到左開始排除set_real_ip_from里面出現的IP,如果出現了未出現這些ip段的IP,那么這個IP將被認為是用戶的IP。例如我這邊的例子,真實服務器獲取到的IP地址串如下:
120.22.11.11,61.22.22.22,121.207.33.33,192.168.50.121
在real_ip_recursive on的情況下
61.22.22.22,121.207.33.33,192.168.50.121都出現在set_real_ip_from中,僅僅120.22.11.11沒出現,那么他就被認為是用戶的ip地址,並且賦值到remote_addr變量
在real_ip_recursive off或者不設置的情況下
192.168.50.121出現在set_real_ip_from中,排除掉,接下來的ip地址便認為是用戶的ip地址
如果僅僅如下配置:
set_real_ip_from 192.168.50.0/24; set_real_ip_from 127.0.0.1; real_ip_header X-Forwarded-For; real_ip_recursive on;
訪問結果如下:
121.207.33.33
4、三種在CDN環境下獲取用戶IP方法總結
4.1 CDN自定義header頭
- 優點:獲取到最真實的用戶IP地址,用戶絕對不可能偽裝IP
- 缺點:需要CDN廠商提供
4.2 獲取forwarded-for頭
- 優點:可以獲取到用戶的IP地址
- 缺點:程序需要改動,以及用戶IP有可能是偽裝的
4.3 使用realip獲取
- 優點:程序不需要改動,直接使用remote_addr即可獲取IP地址
- 缺點:ip地址有可能被偽裝,而且需要知道所有CDN節點的ip地址或者ip段
轉自
(28條消息) 后端nginx使用set_real_ip_from獲取用戶真實IP_zwmnhao1980的博客-CSDN博客_nginx set_real_ip_from
https://blog.csdn.net/zwmnhao1980/article/details/82267921