python-3.x - python3 aiohttp服务器在nginx后面获取不到真实ip

标签 python-3.x nginx aiohttp

我在 nginx 后面使用 aiohttp ( http://aiohttp.readthedocs.io/en/stable/ ) 和 https:

我尝试在 aiohttp 中间件中获取 IP:

peername = request.transport.get_extra_info('peername')
host, port, = (peername if peername is not None else ('',''))

我期待真正的 IP,但它总是返回 127.0.0.1 出现此问题的原因是什么以及如何解决?

我的 nginx 配置文件:

upstream site_python {
        ip_hash;
        server 127.0.0.1:8080;
        server 127.0.0.1:8081;
        server 127.0.0.1:8082;
        server 127.0.0.1:8083;
    }



server {
    listen      11.111.11.111:80;
    server_name www.example.com example.com;
    rewrite     ^   https://$server_name$request_uri? permanent;
}



server {


    listen      11.111.11.111:443 ssl;

    ssl_certificate     /home/site/ssl/www_site_ru.crt;
    ssl_certificate_key /home/site/ssl/561457962.key;
    ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers         HIGH:!aNULL:!MD5;


    server_name www.example.com; 
#    rewrite     ^ http://www.example.com$request_uri permanent;



  if ($host != 'www.example.com') {
    rewrite ^/(.*)$ $scheme://www.example.com$request_uri permanent;
  }



    location / {
        proxy_pass http://site_python$request_uri;
        proxy_redirect off;
        proxy_set_header Host www.example.com;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;    

    }

}

我也尝试在extra中找到它,但里面也没有真正的IP。

print(request.transport._extra)

{'sockname': ('127.0.0.1', 8080), 'socket': <socket.socket fd=32, family=AddressFamily.AF_INET, type=2049, proto=6, laddr=('127.0.0.1', 8080), raddr=('127.0.0.1', 48154)>, 'peername': ('127.0.0.1', 48154)}

最佳答案

我用它来解决

host = request.headers.get('X-FORWARDED-FOR',None)

关于python-3.x - python3 aiohttp服务器在nginx后面获取不到真实ip,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45768661/

相关文章:

nginx - 打开resty : problems with the init_by_lua directive (getting "directive is not allowed here")

redirect - 特定子页面的 Nginx/Django SSL 配置

jsp - session ID 定期更改 (nginx/tomcat/mamcached/MSM)

python - 如何使用 PyCharm 运行 adev(aiohttp_devtools) 命令

python - 创建列表列表的列表以对文本文件中的数据进行排序

python - 在 Windows 中设置 python 3 环境的简单方法 : just install from python. org,或者真的会从 miniconda 或类似的东西中受益吗?

python - 使用 aiohttp 转储请求 header

python - 如何在 Python 中使用 aiohttp 读取流式 api 的行?

bash - 如何使用 Azure 文件共享中的多个线程将数据复制到 Azure Data Lake 存储?

python - xlsxwriter 条件格式 icon_set 中间值 = 0 未显示正确的箭头