Logging in NGINX

Logging is extremely important as it allows us to view errors, malicious users and bots.

There are 2 types of logs - access logs and error logs. As the name suggests, error logs are used to log errors and warnings. Access logs log all requests to the server.

Logging is enabled by default. There is a default log format that you can use without changes. The main NGINX logs are present in /var/log/nginx.

Note that 404 errors are logged to the access log, not the error log.

Configure Logging

Logging Directives

There are 2 directives for logging: access_log and error_log.

Disable logging

It is recommended to disable access logs wherever it is not required. This can save disk space and overhead.

access_log off;

Logging example

Here is a server block with logging enabled in it's location block:

server {

    listen 80;
    server_name melvincv.com;

    root /sites/mcv;

    location /secure {
      # Add context specific log
      access_log /var/log/nginx/access.mcv.log;
      error_log /var/log/nginx/error.mcv.log;
      # Disable logs for context
      #access_log off;
      return 200 "Welcome to secure area.";

Log format configuration

log_format combined '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent"'; access_log /var/log/nginx/access.log combined;

The log_format directive defines the format of the log messages. The combined format is a predefined format that logs the following information:

  • The IP address of the client

  • The username of the client (if authenticated)

  • The time the request was received

  • The requested URL

  • The HTTP status code

  • The number of bytes sent to the client

  • The HTTP referer (the URL of the page that linked to the requested resource)

  • The HTTP user agent (the browser or other application that made the request)

The access_log directive specifies the location of the access log and the format of the log messages. In this example, the access log is located at /var/log/nginx/access.log and the format is the combined format.

Once you have configured NGINX to log the appropriate information, you can start analyzing the access logs to gain insights into the traffic to your website.