0
点赞
收藏
分享

微信扫一扫

nginx屏蔽HEAD OPTIONS请求方法日志

2020-04-13 发表者 Venus

比如nginx日志里有options方法的请求,对分析日志没实际作用,就需要在记录日志时候屏蔽掉。

{“remote_addr”:”192.168.1.141″,”X-Forwarded-For”:””,”remote_user”:””,”time_local”:”13/Apr/2020:09:58:28 +0800″,”request”:”OPTIONS /login HTTP/1.1″,”method“:”OPTIONS”,”uri”:”/login”,”server_protocol”:”HTTP/1.1″,”request_body”:”userid=11″,”status”:”200″,”body_bytes_sent”:”0″,”http_referer”:””,”user_agent”:”PostmanRuntime/7.24.0″,”upstream_response_time”:”0.006″}

网上有说用if判断请求方法是options,则不记录日志(access_log off),不生效,不是无效,是配置的位置不对。

# 演示下错误的配置方法

server
{
listen 80;
server_name admin;

access_log /usr/local/nginx/logs/admin_access.log;
error_log /usr/local/nginx/logs/admin_error.log;

if ($request_method = "OPTIONS")
{
access_log off;
}

location /
{
proxy_pass http://192.168.10.60:10102;
}

# 重启nginx

(base) [root@localhost vhost]# /usr/local/nginx/sbin/nginx -t
nginx: [emerg] "access_log" directive is not allowed here in /usr/local/nginx/conf/vhost/admin.conf:11

这个提示就是说access_log配置指令不允许出现在这里。

官方文档表明,access_log 是允许出现在 http, server, location, if in location, limit_except 这几个配置段中。

如果用了if判断,则需要配置在location中。

# 正确方式

server
{
listen 80;
server_name admin;

access_log /usr/local/nginx/logs/admin_access.log;
error_log /usr/local/nginx/logs/admin_error.log;

location /
{
proxy_pass http://192.168.10.60:10102;

if ($request_method = "OPTIONS")
{
access_log off;
}
}
}

如果有多个方法需要屏蔽可以用正则,比如屏蔽options和head方法

if ($request_method ~* OPTIONS|HEAD)
{
access_log off;
}

这样才可以实现不记录OPTIONS方法日志。

第二种方式:

map $request_method $m {
OPTIONS 0;
HEAD 0;
default 1;
}

server
{
listen 80;
server_name admin;

location /
{
proxy_pass http://192.168.10.60:10102;
}

access_log /usr/local/nginx/logs/admin_access.log combined if=$m;
error_log /usr/local/nginx/logs/admin_error.log;
}

server
{
listen 80;
server_name api;

location /
{
proxy_pass http://192.168.10.60:10103;
}
access_log /usr/local/nginx/logs/api_access.log combined if=$m;
error_log /usr/local/nginx/logs/api_error.log;

}

通过map指令设置自定义变量(map指令由ngx_http_map_module模块提供,默认安装。)

The ngx_http_map_module module creates variables whose values depend on values of other variables.

注意map指令只能在http{}段中出现。对所有虚拟主机都可以直接用。

官方文档中关于access_log的参数:

access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];

The if parameter (1.7.0) enables conditional logging. A request will not be logged if the condition evaluates to “0” or an empty string. In the following example, the requests with response codes 2xx and 3xx will not be logged:

map $status $loggable {
~^[23] 0;
default 1;
}

access_log /path/to/access.log combined if=$loggable;

意思是如果用if参数,后面需要跟着一个变量,这个变量如果是0或者是空字符串,则不会记录日志。

上面的第二种方法就是通过map+access_log中if参数实现的。

举报

相关推荐

0 条评论