1. 程式人生 > >Django Nginx反代 獲取真實ip

Django Nginx反代 獲取真實ip

sts conf 獲取 pip style mon else 整數 real

非反代情況下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 }
xxx.conf

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
views.py

需要時請求此函數即可

ip = get_client_ip(request)

另外ip整數和點分十進制轉換函數附上(pip install inet_ntoa)

技術分享
1 def long2ip(ip):
2     return inet_ntoa(pack("!L", ip))
long2ip 技術分享
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]
ip2long

由ip地址獲得所在地

技術分享
1 def come_from(ip):
2     r = requests.get(url=http://freegeoip.net/json/%s % ip) 
3     return r.json()
come_from

Django Nginx反代 獲取真實ip