django 获取用户IP地址
函数实现
def get_client_ip(request):
try:
real_ip = request.META['HTTP_X_FORWARDED_FOR']
regip = real_ip.split(",")[0]
except:
try:
regip = request.META['REMOTE_ADDR']
except:
regip = ""
return regip
问题是会在有的地方不好使,检测发现request.META
根本无key值等于HTTP_X_FORWARDED_FOR
和REMOTE_ADDR
。服务器采用nginx+fastcgi实现。
解决办法
在nginx的fastcgi配置中加入如下:
fastcgi_param REMOTE_ADDR $remote_addr;