使用Nginx和CloudFlare时如何将真实IP传递给Gunicorn?

时间:2014-10-05 18:53:51

标签: django nginx gunicorn cloudflare

我有以下nginx配置:

http {

    ... <content removed for bevity> ...

    # Cloudflare
    set_real_ip_from   199.27.128.0/21;
    set_real_ip_from   173.245.48.0/20;
    set_real_ip_from   103.21.244.0/22;
    set_real_ip_from   103.22.200.0/22;
    set_real_ip_from   103.31.4.0/22;
    set_real_ip_from   141.101.64.0/18;
    set_real_ip_from   108.162.192.0/18;
    set_real_ip_from   190.93.240.0/20;
    set_real_ip_from   188.114.96.0/20;
    set_real_ip_from   197.234.240.0/22;
    set_real_ip_from   198.41.128.0/17;
    set_real_ip_from   162.158.0.0/15;
    set_real_ip_from   104.16.0.0/12;
    set_real_ip_from   2400:cb00::/32;
    set_real_ip_from   2606:4700::/32;
    set_real_ip_from   2803:f800::/32;
    set_real_ip_from   2405:b500::/32;
    set_real_ip_from   2405:8100::/32;
    real_ip_header     CF-Connecting-IP;

    upstream myproject {
        server unix:/var/www/myproject/gunicorn.sock fail_timeout=0;
    }

    server {

        listen XXX;
        server_name XXXXXX;

        ... <content removed for bevity> ...

        location / {
            proxy_set_header HOST $http_host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_redirect off;
            proxy_pass http://myproject;
        }

    }

然而在Django中,以下代码对我没有任何回报:

request.META.get('REMOTE_ADDR', '') # this gives me b''

如何使用用户的真实IP地址填充REMOTE_ADDR

注意:当我删除nginx配置的#Cloudflare部分时,REMOTE_ADDR会填充Cloudflare的IP地址。


更新:我已将以下内容添加到我的nginx配置中,但request.META.get('REMOTE_ADDR')仍为空。

location / {
    ...
    proxy_set_header REMOTE_ADDR $proxy_add_x_forwarded_for;
}

1 个答案:

答案 0 :(得分:1)

CloudFlare附加 X-Forwarded-For X-Forwarded-Proto 标头。您可以获取并使用X-Forwarded-For来记录客户的IP或传递给另一个代理或任何您想要的代理。

来源:https://support.cloudflare.com/hc/en-us/articles/200170946-Does-CloudFlare-include-an-X-Forwarded-For-header-