在 Nginx 日志中,您可以通过检查日志中的某些字段来区分 HTTP 和 HTTPS 请求
- 首先,确保您的 Nginx 配置文件(通常位于 /etc/nginx/nginx.conf 或 /etc/nginx/sites-available/ 目录下的虚拟主机配置文件)包含以下两个 server 块:
http { ... } https { ... }
- 在 http 块中,添加一个 log_format 指令,用于定义日志格式。例如:
http { log_format my_custom_format '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent" ' 'is_https=$is_https'; ... }
在这个例子中,我们定义了一个名为 my_custom_format 的日志格式,其中包含一个字段 is_https,用于标识请求是否为 HTTPS。
- 在 https 块中,添加一个 proxy_set_header 指令,将 is_https 变量设置为 “on”。例如:
https { ... proxy_set_header X-Forwarded-Proto $scheme; ... }
这里,我们使用 Nginx 的 $scheme 变量将其设置为 “https”。
- 为了在日志中区分 HTTP 和 HTTPS 请求,您需要将 my_custom_format 应用到您的 server 块中。例如:
http { ... access_log /var/log/nginx/access.log my_custom_format; ... } https { ... access_log /var/log/nginx/access_https.log my_custom_format; ... }
这将分别记录 HTTP 和 HTTPS 请求到不同的日志文件中。
现在,当您查看 Nginx 日志时,可以通过检查 is_https 字段来区分 HTTP 和 HTTPS 请求。例如,在 my_custom_format 中,HTTP 请求将显示 is_https=off,而 HTTPS 请求将显示 is_https=on。