nginx作为web服务如果前端没有加负载均衡则nginx服务的访问日志文件中显示的IP地址为客户端的IP地址,但是web服务前面加了负载均衡之后访问日志中拿到的IP为负载均衡的IP地址,有时需要知道客户端的外网IP地址,如遇到恶意的访问时,以下描述具体的获取客户端的外网IP地址和禁用客户端某个IP地址。
1. 前端负载均衡配置
保证nginx前端负载均衡有如下配置,才可在后端nginx中拿到客户端外网IP地址:
location / {
proxy_set_header X-Real-IP $remote_addr;
}
网易蜂巢的负载均衡中此项默认已经配置。、
2. web服务配置
修改格式如下:
log_format main ‘$remote_addr - $remote_user [$time_local] "$request” ’ #访问日志的格式
‘$status $body_bytes_sent “$http_referer” ’
‘”$http_user_agent" "$http_x_forwarded_for”’;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
deny 114.113.197.131; #禁止访问的IP地址
#此地址为负载均衡(蜂巢上为默认拿到的IP,即负载均衡的内网IP)的IP地址
set_real_ip_from 10.173.36.128;
real_ip_header X-Real-IP;
}
}
</code></pre>
reload web服务,外网访问负载均衡IP地址,查看access.log的IP是否已经是外网的IP地址。
3. 参考链接
http://www.111cn.net/sys/nginx/63713.htm
http://www.linux178.com/web/nginx-get-realip.html