Nginx: Forcing upstream server to log proxy server's request id instead of it's own request id

BentCoder asked:

I’ve setup a proxy server that forwards client requests to an upstream server which works fine so far. However, the issue I am trying to solve is that forcing upstream server to log the request id of the proxy server. Is this possible? Just to let you know the $_SERVER variable of upstream server contains [HTTP_X_REQUEST_ID] => 84708dd39a6c0c91e0d1a97404b40f75

PROXY SERVER

CONFIG

server {
    ...

    add_header              X-Request-ID       $request_id;
    proxy_set_header        X-Request-ID       $request_id;

    location ~ ^/api/(.*) {
        proxy_pass http://192.168.0.1:8080/$1$is_args$args;
    }

    ...
}

LOG FORMAT

log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                '$status $body_bytes_sent "$http_referer" '
                '"$http_user_agent" "$http_x_forwarded_for" "$request_id"';

LOG

172.17.0.1 ...... "84708dd39a6c0c91e0d1a97404b40f75"

UPSTREAM SERVER

CONFIG

server {
    location ~ ^/index\.php(/|$) {
        fastcgi_pass php_server:9000;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT $realpath_root;
        internal;
    }
}

LOG FORMAT

log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                '$status $body_bytes_sent "$http_referer" '
                '"$http_user_agent" "$http_x_forwarded_for" "$request_id"';

LOG

172.20.0.1 ...... "172.17.0.1" "7376e0cead9741e7ec07a9194efc80e6"

EXPECTED LOG

172.20.0.1 ...... "172.17.0.1" "84708dd39a6c0c91e0d1a97404b40f75"

My answer:


You don’t actually want the upstream server to log the request ID in $request_id. Instead you want it to log the contents of an HTTP request header named X-Request-ID.

In that case you should log the variable corresponding to that HTTP request header instead: $http_x_request_id.


View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.