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

本文介绍了如何在Nginx中自定义log_format,如yuedu和default,并演示如何为web站点分配不同的日志格式。重点讲解了如何使用$http_xxx_yyy打印特定字段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

官方文档地址:
http://nginx.org/en/docs/http/ngx_http_log_module.html

一、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  $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

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;
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值