020_nginx禁止ip默认参数是$remote_addr无法禁止真实ip的问题

由于网站使用了cdn所以$remote_addr获取的ip是cdn的ip,我现在先禁止某些ip访问发现无法禁止cdn传递过来的客户端的ip也就是$http_x_forwarded_for这个参数。

比如我的日志格式这样的:

log_format main '$http_x_forwarded_for $remote_addr - $remote_user [$time_local] "$request" '

'$status $body_bytes_sent "$http_referer" '

'"$http_user_agent" "$upstream_addr" up:$upstream_response_time-$request_time $upstream_http_content_length';

记录的日志:

140.207.197.63 10.1.60.250 - - [20/Aug/2015:17:18:39 +0800] "HEAD / HTTP/1.1" 403 0 "-" "Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322) 360JK yunjiankong 329117" "10.1.60.151:8080" up:0.006-0.231 14393

我想拒绝所有只允许140.207.197.63这个ip访问

allow 10.1.60.0/24;

allow 140.207.197.63;

deny all;

但是140.207.197.63访问却是403,10.1.60.0/24这个内网里面的ip访问却是正常的,于是乎发现nginx默认禁止的是$remote_addr参数而不是$http_x_forwarded_for。

那就想办法把cdn传递过来的真是ip变量$http_x_forwarded_for传递给$remote_addr,那就用到了这个模块--with-http_realip_module,编译安装的时候要启用。加上下面两个参数:

set_real_ip_from 10.1.60.250;

real_ip_header X-Forwarded-For;

意思就是所有来自10.1.60.250请求的header字段都改成X-Forwarded-For。这样就把真实ip传递给$remote_addr变量了。

它就是把x_forwarded_for设为remote_addr,而nginx里的x_forwarded_for取的就是其中第一个IP。

使用这些设置就能保证你的remote_addr里设定的一直都是客户端的真实IP。

然后再次访问:

140.207.197.63 10.1.60.250 - - [20/Aug/2015:17:18:39 +0800] "HEAD / HTTP/1.1" 200 0 "-" "Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322) 360JK yunjiankong 329117" "10.1.60.151:8080" up:0.006-0.231 14393