我正在尝试使用条件 access_logging 配置 nginx/1.13.0。
如果 access_logging 仅以 $status 代码为条件,则一切正常:
http {
[..]
map $status $logworthy_status {
~^[4] 1;
default 0;
}
[..]
server {
[..]
access_log /var/log/nginx_access.log combined if=$logworthy_status;
[..]
}
}
调试日志显示 map 的行为符合预期:
2017/06/13 11:34:14 [debug] 23153#0: *203 http map started
2017/06/13 11:34:14 [debug] 23153#0: *203 http script var: "401"
2017/06/13 11:34:14 [debug] 23153#0: *203 http map: "401" "1"
但是,如果我尝试重写它以允许多个条件,如建议 here :
http {
[..]
map $status $logworthy_status {
~^[4] 1;
default 0;
}
[..]
server {
[..]
set $logworthy 0;
if ( $logworthy_status = 1 ) {
set $logworthy 1;
}
access_log /var/log/nginx_access.log combined if=$logworthy;
[..]
}
}
不生成日志消息。检查调试日志显示,即使是 $status 上的映射似乎也搞砸了:
2017/06/13 11:38:12 [debug] 23631#0: *204 rewrite phase: 0
2017/06/13 11:38:12 [debug] 23631#0: *204 http script value: "0"
2017/06/13 11:38:12 [debug] 23631#0: *204 http script set $logworthy
2017/06/13 11:38:12 [debug] 23631#0: *204 http script var
2017/06/13 11:38:12 [debug] 23631#0: *204 http map started
2017/06/13 11:38:12 [debug] 23631#0: *204 http script var: "000"
2017/06/13 11:38:12 [debug] 23631#0: *204 http map: "000" "0"
2017/06/13 11:38:12 [debug] 23631#0: *204 http script var: "0"
2017/06/13 11:38:12 [debug] 23631#0: *204 http script value: "1"
2017/06/13 11:38:12 [debug] 23631#0: *204 http script equal
2017/06/13 11:38:12 [debug] 23631#0: *204 http script equal: no
2017/06/13 11:38:12 [debug] 23631#0: *204 http script if
2017/06/13 11:38:12 [debug] 23631#0: *204 http script if: false
有人可以解释一下吗?请求按预期处理,nginx 返回 401,但没有记录。
最佳答案
您可以使用多个 map
具有来自前一个 block 的默认值的指令。例如,记录 4xx 状态请求,其中 User-Agent 不包含“AppleWebKit”
map $status $loggable_status {
~^[4] 1;
default 0;
}
map $http_user_agent $loggable_user_agent {
~*AppleWebKit 0;
default $loggable_status; # Use map var above as default
}
access_log /var/log/nginx/error.log combined if=$loggable_user_agent;
关于Nginx:登录多个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44520875/