Nginx多层代理获取真实IP配置与原理
问题背景
当Nginx处于多层代理架构中时,直接使用$remote_addr变量获取的是直接连接的上层代理服务器IP,而非终端用户的真实IP。此时,$http_X_Forwarded_For头部才包含完整的用户真实IP信息。
解决方案概述
需在Nginx配置文件的http模块中添加相关指令以启用真实IP识别功能。
set_real_ip_from 172.17.10.125; #上一层代理IP地址
real_ip_header X-Forwarded-For;
real_ip_recursive on;
若未正确配置或模块缺失,启动Nginx时可能会报错。
nginx: [emerg] unknown directive "set_real_ip_from" in /home/lnidmp/nginx/conf/nginx.conf:26
解决该问题的关键在于确保Nginx已加载http_realip_module模块。如果当前版本未包含此模块,需重新编译Nginx源码以集成该功能。
首先,进入Nginx源码目录,例如:cd /usr/local/nginx-1.15.12
执行configure命令,确保包含--with-http_realip_module参数,同时保留其他必要模块如stub_status和ssl:./configure --prefix=/usr/cmcc/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_realip_module
完成配置后,执行make && make install进行编译和安装。
关键配置参数说明
set_real_ip_from用于指定信任的前置代理IP地址或网段,只有来自这些信任源的请求才会被处理以获取真实IP。
real_ip_header定义从哪个HTTP请求头部字段中提取前代理传递的用户IP信息,常见值为X-Real-Ip或X-Forwarded-For。
real_ip_recursive控制是否递归地排除信任列表中的IP以找到最终用户IP,默认关闭(off)。
real_ip_header指定一个HTTP首部名称,默认为X-Real-Ip。当Nginx接收到报文后,会检查该首部内容。
若X-Real-Ip中只有一个IP值,Nginx会核对发送方IP是否在set_real_ip_from指定的信任列表中。若匹配,则将该IP视为用户真实IP并赋值给$remote_addr;若不匹配,则保持$remote_addr为发送方IP不变。
若X-Real-Ip包含多个IP值,通常由前置代理通过proxy_set_header X-Real-Ip $proxy_add_x_forwarded_for;设置生成。
当存在多个IP时,real_ip_recursive的值至关重要。Nging将从右向左遍历IP列表,并与set_real_ip_from的信任列表进行比较。
若real_ip_recursive设置为off,当最右侧的IP被确认为信任IP时,其左侧相邻的IP(即右边第二个)将被认定为用户的真实IP。
若real_ip_recursive设置为on,Nginx将从右向左依次比较,直到找到一个不在信任列表中的IP为止。
确定最终用户IP后,Nginx将其赋值给$remote_addr变量,供后续日志记录和访问控制使用。
生产环境Nginx配置文件示例如下:
user www;
worker_processes 10;
worker_rlimit_nofile 51200;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
error_log /data/logs/nginx_error.log crit;
#pid logs/nginx.pid;
events {
use epoll;
worker_connections 51200;
}
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"';
#access_log logs/access.log main;
server_names_hash_bucket_size 128;
server_tokens off;
expires 1h;
sendfile off;
tcp_nopush on;
fastcgi_connect_timeout 1200s;
fastcgi_send_timeout 1200s;
fastcgi_read_timeout 1200s;
fastcgi_buffer_size 128k;
fastcgi_buffers 8 128k;#8 128
fastcgi_busy_buffers_size 256k;
fastcgi_temp_file_write_size 256k;
keepalive_timeout 65;
tcp_nodelay on;
error_page 404 /;
gzip on;
gzip_min_length 2048;
gzip_buffers 4 16k;
gzip_http_version 1.1;
gzip_types text/plain css html application/xml application/x-javascript ;
set_real_ip_from 上一层代理IP地址;
real_ip_recursive on;
real_ip_header X-Forwarded-For;
log_format access '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" $http_x_forwarded_for';
#################### include ################################################
include conf.d/*.conf;
}
以上即为Nginx在多层代理环境下获取真实IP的配置方法与原理详解。