Nginx 获取真实IP地址
项目背景
Nginx 部署在 ECS上, ECS 前端有阿里云 SLB 做负载,nginx 需要获取客户端的真实 IP 进行单独限制
# 重新编译 Nginx
cd /data/tools/nginx-1.13.7
./configure --prefix=/usr/local/nginx --with-threads --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-http_ssl_module
make
cp /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.bak
pkill nginx
cp objs/nginx /usr/local/nginx/sbin/
/usr/local/nginx/sbin/nginx -t
/usr/local/nginx/sbin/nginx
# 查看是否成功
/usr/local/nginx/sbin/nginx -V
修改 Nginx 配置
cat a.klvchen.com.conf
server {
listen 80;
server_name a.klvchen.com;
client_max_body_size 100m;
proxy_connect_timeout 180;
proxy_read_timeout 180;
location / {
proxy_pass http://192.168.0.198:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
set_real_ip_from 0.0.0.0/0; # 额外增加的配置
real_ip_header X-Forwarded-For; # 额外增加的配置
real_ip_recursive on; # 额外增加的配置
allow 192.168.0.168;
deny all;
}
}
可以在 Nginx access.log 中查到真实的客户端IP已出来
tail -f /usr/local/nginx/logs/access.log
参考:
http://nginx.org/en/docs/http/ngx_http_realip_module.html