1 nginx 配置
#配置多层反向代理,配置如下
proxy_pass http://ip或者域名/;
proxy_connect_timeout 60;
proxy_send_timeout 60;
proxy_read_timeout 60;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_http_version 1.1;
2 nginx 日志配置
#vim conf/nginx.conf
log_format access '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" $http_x_forwarded_for $request_time ddr$upstream_response_time $upstream_cache_status $upstream_addr $http_x_forwarded_for $proxy_add_x_forwarded_for';
3 访问网址
4 在转后的服务器,查看日志
#$proxy_add_x_forward,对应的有2个IP ,以逗号分隔,第一个IP 为客户端真实IP,第二个为代理服务器IP地址。
5 X-Forwarded-For获取第一个IP地址
#修改nginx配置,如下
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
map $proxy_add_x_forwarded_for $client_ip {
default "";
~^(?<first_ip>[^,]+),?.*$ $first_ip;
}
server {
listen 80;
server_name localhost;
location /firstip {
default_type text/plain;
charset utf-8,gbk;
return 200 "{\"第一个IP地址\":\"$client_ip\"}";
}
location / {
root html;
index index.html index.htm;
}
}
#
#map $proxy_add_x_forwarded_for $client_ip ,使用map 创建新变量client_ip
# ~^(?<first_ip>[^,]+),?.*$ $first_ip,正则表达式匹配proxy_add_x_forwarded_for,获取逗号之前的IP地址,并存在变量$first_ip里
#default ""; 如果$proxy_add_x_forwarded_for 没有值,则设置值为空
#return 200 "{\"第一个IP地址\":\"$client_ip\"}"; 访问/firstip URL,可以查看客户端原始IP
6 访问查看第一个IP地址
7
标签:map,http,forwarded,ip,获取,add,proxy,IP地址 From: https://blog.csdn.net/tonyhi6/article/details/140102164