Python: Get the visitor's real IP

# 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

If you use nginx reverse proxy , the nginx configuration file needs to add the following content (otherwise you can only get 127.0.0.1):

Nginx saves the client's IP when receiving a direct request from the client, and puts the real IP in the header when requesting the real background, and then the background can get this header. Generally put into REMOTE_ADDRand X-Forwarded-For, the two seem to be different: the former generally only stores the last proxy IP, and the latter concatenates all proxy IPs with commas (the first one is the real IP)

proxy_set_header REMOTE_ADDR $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

Full content:

 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;
        }
    }

After setting the ngnix configuration file, you need to restart nginx.

  1. Determine whether the Nginx configuration is correct. Commands such as: nginx -t -c /usr/nginx/conf/nginx.conf or /usr/nginx/sbin/nginx -t
  2. 重启:/usr/nginx/sbin/nginx -s reload

The parameters of Nginx include: /usr/local/nginx/sbin/nginx can be used like this -parameter-
c <path_to_config>: Use the specified configuration file instead of nginx.conf in the conf directory.
-t: Test whether the configuration file is correct. When the configuration needs to be reloaded during runtime, this command is very important to detect whether the modified configuration file has syntax errors.
-v: Display the nginx version number.
-V: Display the version number of nginx and compile environment information and compile parameters.

 

Guess you like

Origin blog.csdn.net/weixin_38676276/article/details/107991916