linux下nginx获取用户真实IP(高防/WAF/CDN)

安装 nginx时配置编译时需要添加--with-http_realip_module这个参数

cd /usr/local/src    
groupadd  www  #添加www组    
useradd -g  www www -s /sbin/nologin  #创建nginx运行账户www并加入到www组,不允许www用户直接登录系统    
tar  zxvf nginx-1.8.0.tar.gz  
cd nginx-1.8.0    
./configure --prefix=/usr/local/nginx --without-http_memcached_module --user=www --group=www --with-http_stub_status_module --without-http-cache --with-http_ssl_module --with-http_realip_module --with-pcre=/usr/local/src/pcre-8.36

然后我们去nginx配置负载均衡时需要调整iphash,这里需要map模块来映射用户IP到nginx的配置变量上,前期我们通过配置nginx代理模块添加用户真实IP到X-Forwarded-For字段上,这个可以通过后端程序的$_SERVER系统服务中获取到,但是真实的IP在nginx的配置文件中无法获取,所以使用map模块来将这个字段缓存到nginx缓存容器中

map的语法写法如下,直接复制即可:

	map $http_x_forwarded_for $clientRealIp {
		"" $remote_addr;
		~^(?P<firstAddr>[0-9\.]+),?.*$ $firstAddr;
	}

然后我们去负载的服务器中将

iphash
改为
hash $clientRealIp

即可

最后我们还要修改日志格式来存储这个真实的IP日志

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里

proxy_connect_timeout 30s;
proxy_send_timeout   90;
proxy_read_timeout   90;
proxy_buffer_size    32k;
proxy_buffers     4 32k;
proxy_busy_buffers_size 64k;
proxy_redirect     off;
proxy_hide_header  Vary;
proxy_set_header   Accept-Encoding '';
proxy_set_header   Host   $host;
proxy_set_header   Referer $http_referer;
proxy_set_header   Cookie $http_cookie;
proxy_set_header   X-Real-IP  $remote_addr;
proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;

这样nginx和后端程序都能正确获取到用户的真实IP,即使通过,cdn,waf,ddosip几层转发也是一样有效!

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://sulao.cn/post/471.html

我要评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。