Django Nginx反代 获取真实ip
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django Nginx反代 获取真实ip相关的知识,希望对你有一定的参考价值。
非反代情况下Django 中 ip = request.META[‘REMOTE_ADDR‘] 即可拿到对应ip地址
nginx、fcgi、uwsgi等反代情况下
vi /etc/nginx/conf.d/xxx.conf 加入下面几行
location / {
proxy_pass http://127.0.0.1:8080;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header REMOTE_ADDR $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
real_ip_recursive on;
}
完整Nginx配置模板
1 server { 2 listen 80; 3 server_name xxx; 4 access_log /var/log/nginx/xxx.access_log; 5 error_log /var/log/nginx/xxx.error_log; 6 7 location /static/ { 8 alias /data/vhost/xxx/static/; 9 expires 30d; 10 } 11 12 location / { 13 proxy_pass http://127.0.0.1:8080; 14 proxy_redirect off; 15 proxy_set_header Host $host; 16 proxy_set_header REMOTE_ADDR $remote_addr; 17 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 18 real_ip_recursive on; 19 proxy_max_temp_file_size 0; 20 proxy_connect_timeout 90; 21 proxy_send_timeout 90; 22 proxy_read_timeout 90; 23 proxy_buffer_size 4k; 24 proxy_buffers 4 32k; 25 proxy_busy_buffers_size 64k; 26 proxy_temp_file_write_size 64k; 27 } 28 }
Django对应功能模块儿目录下views.py加入
1 def get_client_ip(request): 2 x_forwarded_for = request.META.get(‘HTTP_X_FORWARDED_FOR‘) 3 if x_forwarded_for: 4 ip = x_forwarded_for.split(‘,‘)[-1].strip() 5 else: 6 ip = request.META.get(‘REMOTE_ADDR‘) 7 return ip
需要时请求此函数即可
ip = get_client_ip(request)
另外ip整数和点分十进制转换函数附上(pip install inet_ntoa)
1 def long2ip(ip): 2 return inet_ntoa(pack("!L", ip))
1 def ip2long(ip): 2 """ 3 Convert an IP string to long 4 """ 5 packedIP = socket.inet_aton(ip) 6 return struct.unpack("!L", packedIP)[0]
由ip地址获得所在地
1 def come_from(ip): 2 r = requests.get(url=‘http://freegeoip.net/json/%s‘ % ip) 3 return r.json()
以上是关于Django Nginx反代 获取真实ip的主要内容,如果未能解决你的问题,请参考以下文章