Nginx配置教程:获取用户真实IP

2020年11月23日14:32:48 发表评论 527
由于大多数网站的前端都有CDN或者负载均衡,这样会导致Nginx在获取客户端IP的时候看到的是CDN的IP,而非客户端真实IP。为了解决这个问题需要使用Nginx的realip模块或者proxy_set_header模块,该模块可以从一个指定的请求头中去获取客户端IP信息。 

一、Nginx realip模块的使用 

1、在编译安装nginx的时候加上--with-http_realip_module即可开启该模块。 
2、配置realip模块 
set_real_ip_from CDN_IP;  #设置可信任的IP地址,之后会使用real_ip_header从这些IP中获取请求头信息 
real_ip_header  X-Forwarded-For;  #从X-Forwarded-For头中获取IP地址,多个IP存在时最左边的是客户端IP
3、防止IP地址伪造 
由于X-Forwarded-For已经是通用请求头,恶意攻击可以伪造该请求头进行攻击,这样无法得知攻击者的真实IP。如果Nginx前面还有CDN的话,可以和CDN商协定一个自定义请求头,将真实IP写进日中 

二、Nginx proxy_set_header模块的使用 
配置示例如下: 


location /{   
    proxy_pass http://localhost:8080/web/;   
    #以下三个proxy_set_header配置项是重点   
    proxy_set_header Host $host;   
    proxy_set_header X-Real-IP $remote_addr;   
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;   












     
    

    发表评论

    :?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: