'Invalid input syntax for type inet' db error in Django app with postgres and Gunicorn+Nginx as reverse proxy

前端 未结 3 855
小鲜肉
小鲜肉 2020-12-22 02:22

Can you help me decipher this rather esoteric error? Everything\'s fine when I fire up the application, but crashes the moment I try to login.

相关标签:
3条回答
  • 2020-12-22 02:43

    Adding a custom middleware solved it:

    class XForwardedForMiddleware():
        def process_request(self, request):
            if request.META.has_key("HTTP_X_FORWARDED_FOR"):
                request.META["HTTP_X_PROXY_REMOTE_ADDR"] = request.META["REMOTE_ADDR"]
                parts = request.META["HTTP_X_FORWARDED_FOR"].split(",", 1)
                request.META["REMOTE_ADDR"] = parts[0]
    
    0 讨论(0)
  • 2020-12-22 02:50

    You are not forwarding proxy IP. Here is my set of forwarded headers I set in my nginx config:

    location / {
        proxy_set_header    Host                    $http_host;
        proxy_set_header    User-Agent              $http_user_agent;
        proxy_set_header    X-Real-IP               $remote_addr;
        proxy_set_header    X-Forwarded-For         $proxy_add_x_forwarded_for;
        proxy_set_header    X-Forwarded-Proto       $scheme;
        proxy_pass          ......;
    }
    

    More options in nginx docs - http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_set_header

    Then in Django you can do:

    user_ip = request.META['HTTP_X_REAL_IP`] or request.META['REMOTE_ADDR']
    

    Note that X-Forwarded-Proto is necessary when using Django with SSL in which case you will also need to configure Django a bit:

    SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
    

    More in Django docs - https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-SECURE_PROXY_SSL_HEADER

    0 讨论(0)
  • 2020-12-22 02:56

    Your program is trying to add a row to some logging table with empty remote IP. I suppose that when you use reverse proxy the program doesn't know the remote IP, as it's shadowed by proxy's IP.

    As it's empty I suppose the program is trying to ignore proxy's IP, but it does not find any better. It should use X-Forwarded-For header.

    If there's no reasonable IP to log, the program should simply log "NULL" as the IP.

    0 讨论(0)
提交回复
热议问题