Sobes.tech
Junior — Middle

How to determine from the access.log nginx logs which location block handled the user request to serve specific content?

sobes.tech AI

Answer from AI

In the standard access.log of nginx, there is no direct information about which location block handled the request, as logs only record the final result of the request (URL, status, time, etc.).

To determine which location handled the request, you can:

  • Add a variable in nginx configuration that will be logged and indicate the location name. For example, use the set directive inside each location to set a unique identifier.

  • Use the log_format directive to include this variable in the log format.

Example:

log_format custom '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$location_name"';

server {
    location /images/ {
        set $location_name "images_location";
        # ...
    }
    location /api/ {
        set $location_name "api_location";
        # ...
    }
    access_log /var/log/nginx/access.log custom;
}

Thus, the log will show which location handled the request.