过滤位置的日志但允许将请求传递给代理

过滤位置的日志但允许将请求传递给代理

我知道如何过滤某个位置的日志:

# inside a http block
log_format filter '0.0.0.0 - $remote_user [$time_local] "$request"'
                  '$status $body_bytes_sent '
                  '"$http_referer" "$http_user_agent"';

# Inside a server block
location = /my/sensitive/location {
  access_log log/access.log filter;
}

现在,如果我有一个应用服务器,通常应该处理上述过滤的位置,那么请求将由 nginx 单独处理,而不是转发到应用服务器。

简化配置:

server {
  listen 80;
  # ...

  root /my/website/root;
  try_files $uri/index.html $uri.html $uri @app-server;

  location = /my/sensitive/location {
    access_log log/access.log filter;
  }

  location @app-server {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header Host $http_host;
    proxy_redirect off;

    proxy_pass http://my_local_server;
  }
}

我无法将location块放入我的块中location @app-server。我无法将上面的location块转换为if块并将其放入@app-server块中。

那么,我该如何过滤应用服务器正在处理的位置的日志呢proxy_pass

答案1

解决这个问题最简单的方法是将必要的代理配置提取到一个片段,并根据需要将其包含在各个位置。例如:

nginx/snippets/proxy.conf

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_redirect off;

proxy_pass http://my_local_server;

nginx/sites-available/my-host.conf

server {
  listen 80;
  # ...

  root /my/website/root;
  try_files $uri/index.html $uri.html $uri @app-server;

  location = /my/sensitive/location {
    access_log log/access.log filter;
    include snippets/proxy.conf;
  }

  location @app-server {
    include snippets/proxy.conf;
  }
}

然而,我最终实际上所做的只是为整个服务器块启用过滤日志,因为几乎所有请求都需要过滤:

server {
  listen 80;
  # ...

  access_log log/access.log filter;

  root /my/website/root;
  try_files $uri/index.html $uri.html $uri @app-server;

  location @app-server {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header Host $http_host;
    proxy_redirect off;

    proxy_pass http://my_local_server;
  }
}

相关内容