Home  >  Q&A  >  body text

The log display problem after tornado is deployed through nginx reverse proxy

After we deploy the tornado application using the following nginx configuration

upstream frontends {
        server 127.0.0.1:8000;
        server 127.0.0.1:8001;
        server 127.0.0.1:8002;
        server 127.0.0.1:8003;
    }

All IP requests requested in tornado.log will be displayed as 127.0.0.1, similar to the following
[I 130125 21:44:54 web:1447] 200 GET / (127.0.0.1) 16.00ms

How to make the ip address in tornado.log display as a real ip under nginx reverse proxy?

Correct answer: In addition to the correct nginx configuration, more importantly, xheaders=True needs to be set in tornado httpserver
tornado.httpserver.HTTPServer(Application(), xheaders=True)

PHPzPHPz2712 days ago841

reply all(2)I'll reply

  • 大家讲道理

    大家讲道理2017-05-16 17:31:30

    Can be passed in tornado

    self.request.remote_ip

    To get it, but there may be some problems sometimes, see this issue on github: https://github.com/facebook/tornado/i...

    The principle is to read some HTTP headers

    Similarly, the implementation in PHP is as follows:

    function _get_client_ip() {
        $clientip = '';
        if(getenv('HTTP_CLIENT_IP')
            && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            $clientip = getenv('HTTP_CLIENT_IP');
        } elseif(getenv('HTTP_X_FORWARDED_FOR')
            && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
            $clientip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif(getenv('REMOTE_ADDR')
            && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
            $clientip = getenv('REMOTE_ADDR');
        } elseif(isset($_SERVER['REMOTE_ADDR'])
            && $_SERVER['REMOTE_ADDR']
            && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
            $clientip = $_SERVER['REMOTE_ADDR'];
        }
    
        preg_match("/[\d\.]{7,15}/", $clientip, $clientipmatches);
        $clientip = $clientipmatches[0] ? $clientipmatches[0] : 'unknown';
        return $clientip;
    }

    reply
    0
  • 滿天的星座

    滿天的星座2017-05-16 17:31:30

    If it is a reverse proxy, you can add such a configuration to nginx:
    proxy_pass http://frontends;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;

    reply
    0
  • Cancelreply