nginx obtains the real ip of the client

There are many ways to obtain the real IP of the client in nginx, the following are two commonly used methods:

  1. Use the access_log module of nginx to record the request log, and include the real IP information of the client in the log. For example:

log_format mylog '$remote_addr - $remote_user [$time_local] "$request" '
                '$status $body_bytes_sent "$http_referer" '
                '"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log mylog;

In the above configuration, the real IP address of the client is obtained by using the http_x_forwarded_for field. If this field does not exist or is invalid, use the remote_addr field to obtain the client IP address.

  1. Set the proxy_set_header directive in the location block of nginx to specify the HTTP header information that needs to be passed to the backend server. Among them, X-Forwarded-For is a commonly used HTTP header field, which can be used to indicate the real IP address of the client. For example:
location / {
    
    
    proxy_pass http://backend;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

In the above configuration, when Nginx proxies a request to the backend server, it will add the real IP address of the client to the X-Forwarded-For header, and then forward the request to the backend server. The backend server can obtain the real IP address of the client by parsing the X-Forwarded-For field.

Guess you like

Origin blog.csdn.net/weixin_45000409/article/details/131051379