nginx经过多层代理后获取真实来源ip过程详解
问题
nginx取$remote_addr当做真实ip,而事实上,$http_X_Forwarded_For才是用户真实ip,$remote_addr只是代理上一层的地址
解决方案:
在http模块加
set_real_ip_from172.17.10.125;#上一层代理IP地址 real_ip_headerX-Forwarded-For; real_ip_recursiveon;
添加之后启动nginx报错:
nginx:[emerg]unknowndirective"set_real_ip_from"in/home/lnidmp/nginx/conf/nginx.conf:26
需要添加realip模块,重新编译nginx
1、cd/usr/local/nginx-1.15.12
2、./configure--prefix=/usr/cmcc/nginx--with-http_stub_status_module--with-http_ssl_module--with-http_realip_module
3、make&&makeinstall
温馨提示:
1、set_real_ip_from是指接受从哪个信任前代理处获得真实用户ip
2、real_ip_header是指从接收到报文的哪个http首部去获取前代理传送的用户ip
3、real_ip_recursive是否递归地排除直至得到用户ip(默认为off)
首先,real_ip_header指定一个http首部名称,默认是X-Real-Ip,假设用默认值的话,nginx在接收到报文后,会查看http首部X-Real-Ip。
(1)如果有1个IP,它会去核对,发送方的ip是否在set_real_ip_from指定的信任ip列表中。如果是被信任的,它会去认为这个X-Real-Ip中的IP值是前代理告诉自己的,用户的真实IP值,于是,它会将该值赋值给自身的$remote_addr变量;如果不被信任,那么将不作处理,那么$remote_addr还是发送方的ip地址。
(2)如果X-Real-Ip有多个IP值,比如前一方代理是这么设置的:proxy_set_headerX-Real-Ip$proxy_add_x_forwarded_for;
得到的是一串IP,那么此时real_ip_recursive的值就至关重要了。nginx将会从ip列表的右到左,去比较set_real_ip_from的信任列表中的ip。
如果real_ip_recursive为off,那么,当最右边一个IP,发现是信任IP,即认为下一个IP(右边第二个)就是用户的真正IP;
如果real_ip_recursive为on,那么将从右到左依次比较,知道找到一个不是信任IP为止。
然后同样把IP值复制给$remote_addr。
生产nginx配置文件如下:
userwww;
worker_processes10;
worker_rlimit_nofile51200;
#error_loglogs/error.log;
#error_loglogs/error.lognotice;
#error_loglogs/error.loginfo;
error_log/data/logs/nginx_error.logcrit;
#pidlogs/nginx.pid;
events{
useepoll;
worker_connections51200;
}
http{
includemime.types;
default_typeapplication/octet-stream;
#log_formatmain'$remote_addr-$remote_user[$time_local]"$request"'
#'$status$body_bytes_sent"$http_referer"'
#'"$http_user_agent""$http_x_forwarded_for"';
#access_loglogs/access.logmain;
server_names_hash_bucket_size128;
server_tokensoff;
expires1h;
sendfileoff;
tcp_nopushon;
fastcgi_connect_timeout1200s;
fastcgi_send_timeout1200s;
fastcgi_read_timeout1200s;
fastcgi_buffer_size128k;
fastcgi_buffers8128k;#8128
fastcgi_busy_buffers_size256k;
fastcgi_temp_file_write_size256k;
keepalive_timeout65;
tcp_nodelayon;
error_page404/;
gzipon;
gzip_min_length2048;
gzip_buffers416k;
gzip_http_version1.1;
gzip_typestext/plaincsshtmlapplication/xmlapplication/x-javascript;
set_real_ip_from上一层代理IP地址;
real_ip_recursiveon;
real_ip_headerX-Forwarded-For;
log_formataccess'$remote_addr-$remote_user[$time_local]"$request"'
'$status$body_bytes_sent"$http_referer"'
'"$http_user_agent"$http_x_forwarded_for';
####################include################################################
includeconf.d/*.conf;
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。