How do I configure Nginx HTTP logging?

Overview

This article covers how to configure Nginx to log the HTTP fields necessary for applications handling university data. Follow these guidelines to configure web services compliant with IT Standards.

Configuration

Nginx allows you to define a custom log format in /etc/nginx/nginx.conf and then instruct the log engine to use the format. Custom log formats have the syntax of "log_format <name> <data items to log>;".

A log format defines what information to log from each HTTP request. A log format definition in apache2.conf is one line and looks like: LogFormat "<percent codes for data to log>" <custom log name>.

For configurations not behind a load balancer, the X-Forwarded-For header may be omitted. 

Step 1

Open /etc/nginx/nginx.conf. Within the http {  } stanza, define a new log format as follows:

log_format ui-format '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" $http_x_forwarded_for $remote_port $request_length';

Each dollar sign variable represents one datapoint from an HTTP request. For example, $status is the HTTP status code like 200 OK. Headers can be logged using the format $http_headername. $http_x_forwarded_for logs the X-Forwarded-For header value (substitute dashes with underscores in the log format config). A full list of Nginx variables can be found at https://nginx.org/en/docs/http/ngx_http_core_module.html#variables

Step 2

Scroll down the same file, in the http {  } stanza, and fine the line starting with "access_log". By default it may appear as access_log /var/log/nginx/access.log. To use your custom log format, add the log format name to the end of the line. The access_log line should end up as:

access_log /var/log/nginx/access.log ui-format

Step 3

Restart Nginx. The access log at /var/log/nginx/access.log should now start logging the information defined by ui-highrisk-format.

Details

Article ID: 1861
Created
Thu 3/25/21 9:33 AM
Modified
Fri 3/26/21 11:30 AM