How to Log Post Data in NGINX


log post data in nginx

By default, NGINX logs all your requests GET & POST to help you debug your website/application in case of issues. However, it doesn’t log the actual data posted to your web server in a POST request. This can make it difficult to debug POST requests. It can also make it difficult to detect malicious POST requests and attacks.

 

How to Log Post Data in NGINX

Here are the steps to log post data in NGINX. We will use the log_format directive to setup logging of POST data in NGINX.

 

1. Open NGINX config file

Open NGINX config file in a text editor.

You will find it at one of the following locations, depending on the type of installation


/etc/nginx/conf.d/default.conf
/etc/nginx/sites-enabled/default
/etc/nginx/nginx.conf

 


$ sudo vim /etc/nginx/nginx.conf

 

2. Enable logging of POST data

Add the log_format directive in http or server block to define post_data variable which we will use to setup logging of post data.

Also, in your POST URL (e.g post.php) location block use the access_log directive along with the post_data variable defined in log_format directive.

So your server config will look something like

log_format postdata $request_body;

server {
    ...

    location = /post.php {
       access_log  /var/log/nginx/postdata.log  postdata;
       fastcgi_pass php_cgi;
    }
}

 

If the above code doesn’t work for you, try placing the log_format directive in the server block of your configuration file.

 

If you don’t have fastcgi installed, you can try the following code which uses echo_read_request_body

Install echo_read_request_body with the command

$ sudo apt-get install nginx-full

 

and add the following lines to your config file.

location /post.php {
  log_format postdata $request_body;
  access_log /mnt/logs/nginx/my_tracking.access.log postdata;
  echo_read_request_body;
}

 

3. Reload NGINX web server

Test the config file to ensure there are no errors.

$ sudo nginx -t

 

If you get no error message, reload NGINX server to apply changes.

$ sudo service nginx reload

 

That’s it! Now NGINX will automatically log POST data for your website/application.

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!