网站套CDN后,如何获取客户端(访问者)的真实IP地址(以Nginx为例)

在网站CDN之后,日志里获取到的都是CDN的IP地址,我们有的时候需要记录访客数据,就需要获取访客的真实IP地址。

需要修改Nginx网页服务器的配置文件中http块中的代码,在指定位置添加以下代码:

#http块
http {
    #http全局块
    include   mime.types;

    /*需要插入的代码*/

    default_type  application/octet-stream;
    sendfile  on;
    keepalive_timeout 65;
    #server块
    server {
        #server全局块
        listen   8080;
        server_name  localhost;
        #location块
        location / {
            root   html;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

下面列举几种网站获取用户真实IP所用到的请求头:

1、Cloudflare CDN:

set_real_ip_from 0.0.0.0/0;
real_ip_header CF-Connecting-IP;

2、Gcore CDN:

set_real_ip_from 0.0.0.0/0;
real_ip_header X-Forwarded-For;

3、Amazon CloudFront(亚马逊云CDN服务):

set_real_ip_from 0.0.0.0/0;
real_ip_header CloudFront-Viewer-Address;

亚马逊云需要在Amazon Cloudfront控制面板开启CloudFront-Viewer-Address请求头,开启后再将上方代码插入即可获取访客的真实IP;

4、Netlify CDN:

set_real_ip_from 0.0.0.0/0;
real_ip_header X-Nf-Client-Connection-Ip;

Netlify不支持X-Forwarded-For请求头,因此需要使用专用的X-Nf-Client-Connection-Ip请求头获取用户的真实IP;

5、阿里云CDN:

set_real_ip_from 0.0.0.0/0;
real_ip_header Ali-CDN-Real-IP;

上面就是大部分网站获取真实IP所用到的请求头,一般情况下都用X-Forwarded-For请求头获取用户真实IP,除CDN厂商有特殊说明除外。

5 个赞

好好好 huige正好需要

支持一个,博客用的CDN没关注真实IP

不错,学习了