# IP工具类
class IpUtil:
# X-Forwarded-For:简称XFF头,它代表客户端,也就是HTTP的请求端真实的IP,只有在通过了HTTP 代理或者负载均衡服务器时才会添加该项。
@staticmethod
def get_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0] # 多次反向代理后会有多个ip值,第一个ip才是真实ip
else:
ip = request.META.get('REMOTE_ADDR') # 这里获得代理ip
return ip
如果使用nginx反向代理,则nginx配置文件需添加一下内容(否则只能获取127.0.0.1):
nginx在收到客户端直接请求时将客户端的IP保存起来,并在请求真正后台时将真实IP放到header中去,然后后台获取这个头部即可。一般放到REMOTE_ADDR
和X-Forwarded-For
,二者貌似有点区别:前者一般只存放最后一次代理IP,后者则将所有代理IP逗号拼接起来(其中第一个为真正的IP)
proxy_set_header REMOTE_ADDR $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
完整内容:
server {
# 设置网站运行端口
listen 80;
server_name localhost;
location / {
include uwsgi_params;
uwsgi_pass 127.0.0.1:8997;
index index.html index.htm;
client_max_body_size 35m;
proxy_set_header REMOTE_ADDR $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
# 静态文件目录
location /static/ {
alias /root/appname/static/;
index index.html index.htm;
}
}
设置完ngnix配置文件后,需重新启动nginx。
- 判断Nginx配置是否正确命令如:nginx -t -c /usr/nginx/conf/nginx.conf或者/usr/nginx/sbin/nginx -t
- 重启:/usr/nginx/sbin/nginx -s reload
Nginx 的参数包括:可以这样使用 /usr/local/nginx/sbin/nginx -参数
-c <path_to_config>:使用指定的配置文件而不是 conf 目录下的 nginx.conf 。
-t:测试配置文件是否正确,在运行时需要重新加载配置的时候,此命令非常重要,用来检测所修改的配置文件是否有语法错误。
-v:显示 nginx 版本号。
-V:显示 nginx 的版本号以及编译环境信息以及编译时的参数。