SoFunction
Updated on 2025-03-02

Implementation of Nginx to obtain the real IP of the client (real_ip_header)

When using Nginx as a reverse proxy or load balancer, we often need to get the real IP address of the client. However, by default, Nginx's$remote_addrThe IP address recorded by the variable may be the IP of the upstream proxy or load balancer, rather than the IP of the actual client. To ensure that we can correctly obtain and record the real IP of the client, this article will explain how to configure Nginx and debug.

1. Configure Nginx to obtain the real IP of the client

1. Basic configuration instructions

First, we need to make sure Nginx can correctly parse from upstream agents or load balancersX-Forwarded-ForHeader information. By configurationreal_ip_headerandset_real_ip_from, Nginx can convert$remote_addrUpdated to the real IP of the client.

Sample configuration

http {
    include       ;
    default_type  application/octet-stream;
    server_tokens off;

    # Set the header information of the real IP    real_ip_header X-Forwarded-For;

    # Specify the trusted upstream proxy IP range, here 172.0.0.0/8 is an example (that is your load-balanced IP segment)    set_real_ip_from 172.0.0.0/8;

    #Other configurations    ...
}
  • real_ip_header X-Forwarded-For;: Specify which header to get the client's real IP address. Common heads includeX-Forwarded-ForX-Real-IPwait.
  • set_real_ip_from 172.0.0.0/8;: Specifies which IP address segments requests can be trusted. If the request comes from these address segments, then Nginx willreal_ip_headerConfiguration update$remote_addr

In Nginx,set_real_ip_fromThe instruction is used to define which IP addresses or IP address segments are trusted. Depending on the request source, is the IP address inset_real_ip_fromWithin the specified range, Nginx's behavior will be different, the specific differences are as follows:

2. Set_real_ip_from detailed explanation

1. Request source IP inset_real_ip_fromWithin range

If the IP address of the requested source isset_real_ip_fromWithin the specified range, Nginx will trust the request and usereal_ip_headerThe specified header (such asX-Forwarded-ForThe value in ) is used as the client's real IP address.

Behavior:

  • Nginx UseX-Forwarded-ForThe first (leftmost) IP address in the header is$remote_addr(i.e. the real IP address of the client).
  • This usually occurs on the load balancer or reverse proxy server front end, which will addX-Forwarded-ForHead to indicate the real client IP.

2. The source of the request IP is not presentset_real_ip_fromWithin range

If the IP address of the requested sourceNot here set_real_ip_fromWithin the specified range, Nginx will not trust the request.X-Forwarded-ForIP address in the header.

Behavior:

  • Nginx uses the IP address of the request source directly (i.e.$remote_addr) as the client's IP address.
  • This means that Nginx treats the IP address of the load balancer or proxy server as the IP of the client without consideringX-Forwarded-ForThe value in the header.

Scenario analysis:

  • In scope:If you have a load balancer, all requests will pass through it and then arrive at Nginx. The load balancer will be added to the request headerX-Forwarded-ForTo record the client's real IP. If you configure the IP address of the load balancer inset_real_ip_fromIn  Nginx will read and trustX-Forwarded-ForThe real IP of the client in  .

  • Not within range:If the request was not sent through a load balancer you trust (maybe directly accessing Nginx, or from an untrusted proxy server), Nginx will consider the request to beX-Forwarded-ForIt is not trustworthy, so the actual request source IP (the IP address of the load balancer or proxy) is used as the client IP.

3. log_format configuration (reference)

When configuring the log format, you can use it directly$remote_addrVariable. Nginx is analyzingreal_ip_headerAfter that, the$remote_addrReplace with the parsed real IP address.

Log format configuration

log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                '$status $body_bytes_sent "$http_referer" '
                '"$http_user_agent" "$http_x_forwarded_for"';
  • $remote_addr: Configurereal_ip_headerAfter that, this variable will represent the client's real IP address.

2. Debugging and testing

To ensure the configuration is correct, we can use a simple debug log to test it.X-Forwarded-ForContents of the head.

Add debug log

You can use the following configuration toX-Forwarded-ForThe header is recorded in a special debug log file.

Debug log configuration

log_format debug '$http_x_forwarded_for';
access_log /path/to/log/ debug;

Through this configuration, you can view it directly during the debugging process.X-Forwarded-ForContents at the header to confirm whether it contains the client's real IP address.

Check the debug log

After the configuration is complete, restart Nginx and generate some logs by accessing the application. Then, check the debug log/path/to/log/To verifyX-Forwarded-ForThe value of the head.

tail -f /path/to/log/

ifX-Forwarded-ForThe header contains the client's real IP address, which means that the configuration is correct and Nginx can correctly obtain and record the client's real IP.

3. Use the real IP of the client in Lua (reference)

In actual applications, if you use the Lua module of OpenResty or Nginx, you can use it in Lua code..remote_addrTo obtain the parsed real IP.

Sample code

access_by_lua "
local uid = .cookie_bb_id
if not uid then
    uid = ngx.md5(() .. .remote_addr .. .http_user_agent)
    ['Set-Cookie'] = 'bb_id=' .. uid .. '; path=/; Expires=' .. ngx.cookie_time(() + 3650*86400) .. '; Secure; SameSite=None'
end
";

In the above Lua code,.remote_addrThe parsed client's real IP will be obtained. This is very useful in user tracking or logging.

4. Summary

By correct configurationreal_ip_headerandset_real_ip_from, we can ensure that Nginx can pass$remote_addrGet and record the client's real IP address. After the configuration is completed, the debug log can be used to verify that the configuration is in effect. If you need to obtain the real IP in Lua, you can use it directly.remote_addr

This is the article about the implementation of Nginx to obtain the real IP of the client (real_ip_header). For more information about Nginx to obtain the real IP of the client, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!