Nginx可通过log_format记录$scheme变量准确审计HTTP到HTTPS跳转率:$scheme始终反映原始请求协议(http/https),结合$status(301/302)和$upstream_http_location可识别跳转行为,再通过日志分析计算跳转率。

要在 Nginx 中通过 log_format 记录 $scheme 变量来审计站点从 HTTP 到 HTTPS 的跳转率,核心是:确保日志中能准确区分请求原始协议,并结合跳转行为(如 301/302 响应)做统计分析。
确认 $scheme 在日志中可被正确捕获
$scheme 表示客户端发起请求时使用的协议(http 或 https),它由 Nginx 根据请求头或连接方式自动设置,**不依赖于是否配置了 SSL 或是否发生跳转**。因此,只要请求到达 Nginx,该变量就有值。
- HTTP 请求访问
http://example.com/→$scheme为http - HTTPS 请求访问
https://example.com/→$scheme为https - 即使配置了
return 301 https://...,原始请求的$scheme仍是http,可用于识别“跳转源头”
定义含 $scheme 的自定义日志格式
在 http 块中添加:
log_format scheme_log '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$scheme $request_time $upstream_http_location;'关键点:
-
$scheme直接记录原始协议 -
$upstream_http_location可捕获跳转响应头中的Location(如https://example.com/),用于识别是否发生了 3xx 跳转 - 配合
$status(如301或302)可精准定位跳转行为
在 server 块中启用该日志格式
分别对 HTTP 和 HTTPS 的 server 块配置访问日志:
# HTTP server(端口 80)
server {
listen 80;
server_name example.com;
access_log /var/log/nginx/http_access.log scheme_log;
return 301 https://$server_name$request_uri;
}
<h1>HTTPS server(端口 443)</h1><p>server {
listen 443 ssl;
server_name example.com;
ssl_certificate ...;
ssl_certificate_key ...;
access_log /var/log/nginx/https_access.log scheme_log;</p><h1>正常业务处理...</h1><p>}这样就能分离记录两类请求,便于后续对比分析。
用日志分析跳转率(关键指标)
跳转率 = HTTP 请求中触发跳转(301/302)的数量 ÷ 所有 HTTP 请求总数
例如,用 awk 统计过去一小时的跳转率:
# 统计所有 HTTP 请求(来自 http_access.log 中 $scheme == "http")
total_http=$(awk '$9=="http" {count++} END {print count+0}' /var/log/nginx/http_access.log)
<h1>统计 HTTP 请求中返回 301 的数量</h1><p>redirect_301=$(awk '$9=="http" && $6==301 {count++} END {print count+0}' /var/log/nginx/http_access.log)</p><h1>计算跳转率(bash 中需用 bc 或 awk 计算浮点)</h1><p>echo "scale=2; $redirect_301 / $total_http" | bc若结果接近 100%,说明几乎全部 HTTP 流量都被跳转;若明显偏低,需检查是否部分客户端直连 HTTPS、或存在未走 Nginx 的流量路径(如 CDN 缓存了 HTTP 响应)。

















