[DevOps] nginx-转发请求-django如何获得真正的用户IP

184 阅读1分钟

Question

nginx 转发请求, django 如何获得真正的用户 IP?

  1. nginx 配置文件如下, 这样的话, 由于后端代码得到的请求都是本地 nginx 转发的, 因此其获取的 IP 地址也就是127.0.0.1, 是 nginx 所在的 IP 地址
  2. 现在要获得用户请求时候的原始 IP 地址(外网地址), 比如 a.b.c.d
server {
	listen 80;
	server_name www.test.com;
	default_type text/html;
	location / {
	      proxy_pass http://127.0.0.1:8000;
	}
	location ~ ^/static/ {
	    root /opt/test-project;
	}
}
  1. 场景, 后端需要对 IP 地址进行过滤, 但是前端请求都是通过 nginx 转发到本地的后端服务端口,比如 80-> 8000.
  2. 如果通过 django 的 get_ip(request)模块, 得到的 IP 只是 127.0.0.1, 得不到真正的用户 IP 地址

Answer

真正的 IP 地址 nginx 可以取得, 然后转发给后端

方法: nginx 转发真正的 IP 地址给后端, 添加

location / {
	proxy_set_header X-Real-IP $remote_addr; #加上这句话就可以了
	proxy_pass http://127.0.0.1:8000;
}