大网数据广告活动
服务器运维问答

Exclude multiple query parameters from being logged in Nginx?

· 52CE 我爱测

This question is similar to Exclude a specific query parameter from being logged in Nginx? but for multiple parameters. What I want to do is to obfuscate all query parameters, that I specify, that are present in the request URI. …

问题原文

原帖链接 · Johan · CC BY-SA 4.0

This question is similar to Exclude a specific query parameter from being logged in Nginx? but for multiple parameters. What I want to do is to obfuscate all query parameters, that I specify, that are present in the request URI. For example, let's say that I have the following request:

GET /index.html?latitude=55.70&longitude=32.2341&otherkey=value HTTP/1.1

then I would like both latitude and longitude to be obfuscated in the logs:

GET /index.html?latitude=***&longitude=***&otherkey=value HTTP/1.1

If I try defining the log format like this:

log_format  main  '$remote_addr - $remote_user [$time_local] $host "$customrequest" '
                      '$status $body_bytes_sent $request_time "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

map $request $customrequest {
        ~^(.*)([\?&]latitude=|longitude=)([^&]*)(.*)$   "$1$2***$4";
        default                 $request;
}

then only the last parameter in the regex is taken into account and the result will be:

GET /index.html?latitude=55.70&longitude=***&otherkey=value HTTP/1.1

which is not what I want.

So the questing is, how can I configure Nginx to obfuscate all of the given (query/uri) parameters that I've defined?

I'm using Nginx 1.19.5.

已采纳解答

原帖链接 · Richard Smith · CC BY-SA 4.0

You can cascade map statements. It may not be very efficient, but it is easily extended. Also, you will need to use named captures, as the numeric captures will be overwritten.

For example:

map $request $custom1 {
    ~^(?<prefix1>.*[\?&]latitude=)([^&]*)(?<suffix1>.*)$  "${prefix1}***$suffix1";
    default                                               $request;
}
map $custom1 $customrequest {
    ~^(?<prefix2>.*[\?&]longitude=)([^&]*)(?<suffix2>.*)$ "${prefix2}***$suffix2";
    default                                               $custom1;
}

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2020-12-15)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。