使用Nginx自帶的Realip模塊獲取用戶真實IP
(一)簡要說明
如果你的Web服務器前端有代理服務器或CDN時日志中的$remote_addr可能就不是客戶端的真實IP了。比較常用的解決方法有以下三幾種,本文將主要介紹如何使用Nginx自帶realip模塊來解決這一問題
:
1,用CDN自定義IP頭來獲取
2,通過HTTP_X_FORWARDED_FOR獲取IP地址
3,使用Nginx自帶模塊realip獲取用戶IP地址
ngx_realip模塊究竟有什么實際用途呢?為什么我們需要去改寫請求的來源地址呢?答案是:當Nginx處理的請求經過了某個HTTP代理服務器的轉發時,這個模塊就變得特別有用。
當原始用戶的請求經過代理(squid,proxy)轉發之后,nginx接收到的請求的來源地址也就變成了該代理服務器的IP,於是乎nginx 就無法獲取用戶請求的真實IP地址了。
所以,一般我們會在Nginx之前的代理服務器中把請求的原始來源地址編碼進某個特殊的HTTP請求頭中,然后再在Nginx中把這個請求頭中編碼的地址恢復出來。這樣Nginx中的后續處理階段(包括Nginx背后的各種后端應用)就會認為這些請求直接來自那些原始的地址,代理服務器就仿佛不存在一樣。ngx_realip模塊正是用來處理這個需求的。
(二)安裝realip模塊
[root@localhost nginx-1.9.1]#./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-pcre=../pcre-6.6
--with-http_realip_module
[root@localhost nginx-1.9.1]#make
[root@localhost nginx-1.9.1]#make install
(三)配置語法
set_real_ip_from 192.168.1.0/24; #真實服務器上一級代理的IP地址或者IP段,可以寫多行。 set_real_ip_from 192.168.2.1;
real_ip_header X-Forwarded-For; #從哪個header頭檢索出所要的IP地址。
real_ip_recursive on; #遞歸的去除所配置中的可信IP。排除set_real_ip_from里面出現的IP。如果出現了未出現這些IP段的IP,那么這個IP將被認為是用戶的IP。
一下就是配置實例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
server {
listen 80;
server_name localhost;
index index.html index.htm index.php;
#include deny.ip;
access_log
/data/nginx
.access.log;
location ~ .* {
proxy_pass http:
//192
.168.180.20;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
#proxy_set_header X-Forward-For $remote_addr;
proxy_set_header Host $host;
set_real_ip_from 192.168.180.0
/24
;
set_real_ip_from 192.168.181.0
/24
;
real_ip_header X-Forwarded-For;
real_ip_recursive on;
}
}
|
如果服務器獲取的IP地址如下:
192.168.180.4
192.168.181.30
118.242.26.94
在real_ip_recursive on的情況下,192.168.180.4和192.168.181.30這兩個IP地址都在set_real_ip_from中出現,僅僅118.242.26.94沒有出現,那么這個IP就被認為是用戶的IP地址,並且賦值到remote_addr變量。
在real_ip_recursive off或者不設置的情況下,192.168.180.4出現在了set_real_ip_from中會被排除掉,其它的IP地址便認為是用戶的ip地址。
具體的可以參考nginx官方文檔:http://nginx.org/en/docs/http/ngx_http_realip_module.html