天天看點

nginx擷取用戶端真實IP位址

假設公司網站架構為 client ---->nginx 負載均衡--->varnish 緩存---->nginx( web)----->tomcat 請問如何從 nginx(web)這一層的通路日志日志中擷取以下資訊:請求發起的用戶端 IP 以及經過的 nginx 負載均衡和 varnish 緩存的伺服器 IP,看以下架構圖:

[img]http://dl2.iteye.com/upload/attachment/0110/6899/82291637-d8d8-364e-9208-c09211b45ebe.jpg[/img]

在nginx-web伺服器安裝nginx的時候需要把 --with-http_realip_module 該子產品編譯進去,該子產品是用來從前端伺服器發來的頭部資訊中,擷取到用戶端的真實IP位址

nginx負載均衡器上的nginx.conf配置如下(針對本次實驗的配置):

upstream varnish {

server 10.10.10.122;

}

server {

listen 80;

server_name localhost;

location / {

proxy_set_header X-Real-IP $remote_addr;

proxy_pass http://varnish;

}

}

varnish-緩存伺服器上 test.vcl的配置如下:

backend web1 {

.host = "10.10.10.123";

.port = "80";

}

sub vcl_recv {

set req.http.X-Forwarded-For = req.http.X-Forwarded-For + server.ip;

}

sub vcl_fetch {

if(req.request == "GET" && req.url ~ "/"){

set beresp.ttl = 5s;

}

}

sub vcl_deliver {

if (obj.hits >0){

set resp.http.X-cache = "HIT";

} else {

set resp.http.X-cache = "MISS";

}

return(deliver);

}

nginx-web上nginx.conf的配置如下:

日志格式 nginx自帶的日志格式,并未修改

http {

include mime.types;

default_type application/octet-stream;

log_format main '$remote_addr - $remote_user [$time_local] "$request" '

'$status $body_bytes_sent "$http_referer" '

'"$http_user_agent" "$http_x_forwarded_for"';

...

server {

listen 80;

server_name localhost;

location / {

root html;

index index.html index.htm;

set_real_ip_from 10.10.10.122;

real_ip_header X-Real-IP;

}

增加這2行配置

set_real_ip_from 10.10.10.122; 告訴nginx從那邊擷取RealIP的值

real_ip_header X-Real-IP; 存儲RealIP值的變量名稱

從使用者端 10.10.10.46 通路 http://10.10.10.120

[img]http://dl2.iteye.com/upload/attachment/0110/6901/9489650b-a684-3837-b7d1-ac0df6776a02.png[/img]

然後在nginx-web上看日志輸出

[img]http://dl2.iteye.com/upload/attachment/0110/6903/edce84b0-d876-35f5-bbbb-8c3b5fd79767.png[/img]

可以看到第一段就是 用戶端的IP位址,而并不是varnish伺服器的位址,而最後一段裡面,就包含 varnish伺服器的位址 10.10.10.122 和 nginx伺服器的位址10.10.10.120

繼續閱讀