Django Nginx反代 获取真实ip
原创
©著作权归作者所有:来自51CTO博客作者ch3nnn的原创作品,请联系作者获取转载授权,否则将追究法律责任
非反代情况下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配置模板
xxx.conf
server {
listen 80;
server_name xxx;
access_log /var/log/nginx/xxx.access_log;
error_log /var/log/nginx/xxx.error_log;
location /static/ {
alias /data/vhost/xxx/static/;
expires 30d;
}
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;
proxy_max_temp_file_size 0;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffer_size 4k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
}
}
Django对应功能模块儿目录下views.py加入
def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[-1].strip()
else:
ip = request.META.get('REMOTE_ADDR')
return ip
需要时请求此函数即可
ip = get_client_ip(request)
另外ip整数和点分十进制转换函数附上(pip install inet_ntoa)
def long2ip(ip):
return inet_ntoa(pack("!L", ip))
def ip2long(ip):
"""
Convert an IP string to long
"""
packedIP = socket.inet_aton(ip)
return struct.unpack("!L", packedIP)[0]
由ip地址获得所在地
def come_from(ip):
r = requests.get(url='http://freegeoip.net/json/%s' % ip)
return r.json()