nginx自定义log_format以及输出自定义http头

官方文档地址:

http://nginx.org/en/docs/http/ngx_http_log_module.html

一、log_format默认格式 

首先Nginx默认的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"';

二、自定义多个log_format

上面的main标识给log_format取的别名,比如我可以首先定义多个log_format,例如下面的nginx.conf,我就定义了两个log_format,一个别名叫yuedu,一个别名叫default

http
    {
        include       mime.types;
        #include luawaf.conf;

        include proxy.conf;
  
        log_format yuedu '$http_yd_uid $http_yd_token $remote_addr [$time_local] $request_method $http_host $request_uri $status $body_bytes_sent $upstream_response_time "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"';
        log_format default '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"';
  
        default_type  application/octet-stream;
        ......
        include /www/server/panel/vhost/nginx/*.conf;
}

  

三、给web网站分配log_format

在nginx里面新建web站点的时候,可以配置该站点使用的log_format格式,如果不指定log_format,则使用的默认的log_format,如下面这个站点使用是别名为yuedu的log_format

access_log  /www/wwwlogs/xxx.log yuedu;
server
{
    listen 80;
    
    server_name www.xxx.com;
    index index.php index.html index.htm default.php default.htm default.html;
    root /www/wwwroot/xxx;
  
    ......
    access_log  /www/wwwlogs/xxx.log yuedu;
    error_log  /www/wwwlogs/xxx.error.log;
}

  

四、access_log里打印自定义的消息header头

比如现在客户端在http请求里,加入一个新的自定义的header

Yd-Token : 123465

那么在log_format里要打印输出这个header,则只需要取变量$http_yd_token,则可以打印这个header了

log_format yuedu '$http_yd_token ...'

类似的如果要在log_format里打印 Xxx-Yyy这样的消息头,只需要使用$http_xxx_yyy即可

 

原文地址:https://www.cnblogs.com/werben/p/11547856.html