当前位置:首页 > 站长知识 > 服务器 > 正文内容

nginx日志打印请求头信息

2024-12-02服务器29

问题:

发现nginx转发的时候,似乎把在请求头中自定义的字段弄丢了~~,所以想尝试打印出请求头找出具体原因

一、打印nigx请求头

只需要简单改造下nginx.conf中的配置即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
http {
    include       mime.types;
    default_type  application/octet-stream;
 
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_user_id" "$http_accept_language" ';
 
    access_log  logs/access.log  main;
 
    sendfile        on;
    #tcp_nopush     on;
    underscores_in_headers on;
 
    #keepalive_timeout  0;
    keepalive_timeout  65;
    server_names_hash_bucket_size 512;
    client_max_body_size 500m;
    client_header_buffer_size 32k;
    large_client_header_buffers 4 32k;
}

其中改动的位置为

log_format ,打印请求头中的自定义参数为user_id,所以要在配置中添加 “$http_user_id” 没错,带有 $http_ 前缀

access_log logs/access.log main; 使它打印在日志中,查看日志即可

二、但是我的不生效

经过不断尝试,发现一个问题,我的自定义key为 user_id ,但是默认情况下,nginx是不支持下划线字段的!

也就是说如果是 user-id 那么就没问题

我现在需要的字段就是user_id

在nginx.conf中做加入如下配置:

1
underscores_in_headers on;

依然是http模块,上面其实已经有了