Nginx默认不记录OPTIONS预检请求日志,需通过location精确匹配并return 204确保进入log phase;推荐用map标记$is_options变量写入日志便于统计,或结合Prometheus等工具实时监控。

默认情况下,Nginx 不会单独记录 OPTIONS 预检请求(Preflight Request)的访问日志,尤其当它被 if 或 try_files 指令提前拦截、或由 add_header 直接响应时,这些请求可能根本不会进入 log phase。要准确记录并统计 OPTIONS 流量,关键在于确保预检请求真正“经过”日志记录阶段,并区分其与实际业务请求。
确保 OPTIONS 请求进入 access_log 流程
Nginx 的日志写入发生在请求处理的最后阶段(log phase),但若请求被早期指令(如 if ($request_method = 'OPTIONS') { ... } 中的 return 204)直接终止,就可能跳过日志。正确做法是避免在非日志上下文中“吞掉”OPTIONS 请求:
- 用
location块精确匹配 OPTIONS,配合add_header和return 204,该方式仍会触发 access_log(前提是未配置log_not_found off或类似屏蔽) - 避免在 server 或 location 级别使用
if ($request_method = 'OPTIONS')—— 它属于不推荐的“if is evil”场景,且易导致日志遗漏 - 确认
access_log指令位于生效的 location 或 server 块中,而非仅放在未匹配到的默认块里
为 OPTIONS 单独定义日志格式与文件(可选但推荐)
便于后续分析和监控,可将 OPTIONS 请求分离记录:
- 定义专用日志格式,例如:
log_format options_log '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" $request_time'; - 在匹配 OPTIONS 的 location 中启用独立日志:
location = / { if ($request_method = 'OPTIONS') { add_header Access-Control-Allow-Origin "*"; add_header Access-Control-Allow-Methods "GET, POST, OPTIONS"; add_header Access-Control-Allow-Headers "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization"; add_header Access-Control-Max-Age 1728000; add_header Content-Type 'text/plain; charset=utf-8'; add_header Content-Length 0; return 204; } }
access_log /var/log/nginx/options.log options_log; - 注意:上述
if在location = /内属于相对安全的用法(仅用于 method 判断),但仍建议改用map实现更健壮的条件分发
用 map 实现无副作用的 OPTIONS 标识与统计
借助 map 指令,在 rewrite 阶段前就标记请求类型,既不影响流程,又支持灵活统计:
- 在 http 块中定义:
map $request_method $is_options { default 0; OPTIONS 1; } - 在 log_format 中加入该变量:
log_format main '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" $request_time $is_options'; - 这样所有日志行末尾都会带一个
0或1,方便用 awk/grep/ELK 等工具快速聚合:
awk '$13 == 1 {c++} END {print "OPTIONS count:", c+0}' /var/log/nginx/access.log
通过 stub_status 或第三方模块做实时流量统计
若需实时查看 OPTIONS 请求 QPS,原生 stub_status 不区分 method,但可结合以下方式:
- 启用
stub_status后,用 Prometheus + nginx-vts-exporter(支持按 method 统计)采集指标,查询类似nginx_vts_request_total{method="OPTIONS"} - 或使用
ngx_http_api_module(OpenResty)编写简单 Lua 脚本,在处理 OPTIONS 时递增共享字典计数器 - 基础运维场景下,也可用
tail -f /var/log/nginx/access.log | grep '"OPTIONS ' | awk '{print $4}'配合watch观察频率

















