How to log real user’s IP address with Nginx in log files

To log a real user’s IP address with Nginx in log files, you can use the $remote_addr variable. This variable contains the IP address of the user making the request.

Here’s how you can configure Nginx to log the real user’s IP address in the log files:

  1. Open the Nginx configuration file: The Nginx configuration file is usually located at /etc/nginx/nginx.conf. You can edit this file using a text editor such as nano:
sudo nano /etc/nginx/nginx.conf
  1. Configure the log format: Nginx uses a default log format, but you can create a custom log format to include the $remote_addr variable. To do this, add the following code to the Nginx configuration file:
log_format custom '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';

This creates a custom log format that includes the IP address, user, time, request, status code, number of bytes sent, referer, and user agent.

  1. Apply the log format to the access logs: Next, you will need to apply the custom log format to the access logs by adding the following code to the server block in the Nginx configuration file:
access_log /var/log/nginx/access.log custom;

Replace /var/log/nginx/access.log with the path to the access log file you want to use.

  1. Save and close the configuration file: Once you have made the changes, save the file and close the text editor.
  2. Restart Nginx: Finally, you will need to restart Nginx for the changes to take effect. You can do this with the following command:
sudo systemctl restart nginx

Now, when a user makes a request to your Nginx server, the real user’s IP address will be logged in the access log file along with other details. You can view the log file to see the IP addresses of users who have made requests to your Nginx server.

Note: The exact steps to log the real user’s IP address in Nginx log files may vary slightly depending on your setup and configuration. For more information, see the Nginx documentation: https://nginx.org/en/docs/.

Leave a Comment