Nginx · December 18, 2023

Nginx for Newbie: setting up set_real_ip_from directive

Nginx for Newbie: Setting up set_real_ip_from Directive

Nginx is a popular web server and reverse proxy server that is known for its high performance, scalability, and flexibility. It is widely used by many websites and web applications to handle heavy traffic loads efficiently. One of the key features of Nginx is its ability to handle real client IP addresses when it is used as a reverse proxy server.

When Nginx acts as a reverse proxy, it receives requests from clients and forwards them to backend servers. However, by default, Nginx uses its own IP address in the $remote_addr variable to identify the client's IP address. This can be problematic when you need to log or track the real IP addresses of your clients.

To solve this issue, Nginx provides the set_real_ip_from directive, which allows you to specify trusted IP addresses that are used to replace the default IP address in the $remote_addr variable. This directive is particularly useful when Nginx is deployed behind a load balancer or a proxy server.

Configuring the set_real_ip_from Directive

To configure the set_real_ip_from directive, you need to edit the Nginx configuration file. The configuration file is usually located in the /etc/nginx directory and is named nginx.conf or default.conf.

Open the configuration file using a text editor and locate the http block. Inside the http block, add the following line:

set_real_ip_from <trusted IP>;

Replace <trusted IP> with the IP address or IP range that you want to trust. You can specify multiple IP addresses or IP ranges by separating them with spaces. For example:

set_real_ip_from 192.168.0.0/16 10.0.0.1;

Save the configuration file and restart Nginx for the changes to take effect. You can use the following command to restart Nginx:

sudo service nginx restart

Verifying the Configuration

After configuring the set_real_ip_from directive, you can verify if Nginx is correctly replacing the client's IP address. You can do this by checking the value of the $remote_addr variable in your application or by examining the access logs generated by Nginx.

If everything is configured correctly, the $remote_addr variable should contain the real IP address of the client instead of the IP address of the Nginx server.

Conclusion

The set_real_ip_from directive in Nginx is a powerful tool that allows you to accurately identify the real IP addresses of your clients when Nginx is used as a reverse proxy server. By configuring this directive, you can ensure that your logs and tracking systems record the correct client IP addresses, even when Nginx is deployed behind a load balancer or a proxy server.

For more information about Nginx and its features, you can visit the Server.HK website. Server.HK is a leading VPS hosting company that offers reliable and high-performance VPS solutions for businesses of all sizes.