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 如果$http_x_forwarded_for或者$proxy_add_x_forward 包含一个或者多个IP地址,ip地址通过逗号和空格分隔.获取第二个IP地址,可通过nginx map 正则匹配
#修改nginx配置如下
http {
include mime.types;
default_type application/octet-stream;
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$up
stream_response_time $upstream_cache_status $upstream_addr $http_x_forwarded_for $proxy_add_x_forwarded_for'; sendfile on;
keepalive_timeout 65;
map $proxy_add_x_forwarded_for $Second_forwarded_ip {
default "";
~^(?:\d+\.\d+\.\d+\.\d+)(?:,[\s]*)(?<second_ip>\d+\.\d+\.\d+\.\d+).*$ $second_ip;
}
server {
listen 80;
server_name localhost;
access_log /usr/local/openresty/nginx/logs/111.log access;
error_log /usr/local/openresty/nginx/logs_error.log error;
location /secondip {
default_type text/plain;
charset utf-8,gbk;
return 200 "{\"第二个IP地址\":\"$Second_forwarded_ip\"}";
}
location / {
root html;
index index.html index.htm;
}
}
8 访问 url /secondip 查看