SuperAPI AI 工具集

nginx-request-logging

部署与运维

查看项目

更新于 10-15 23:59

技能介绍

该技能用于 Nginx 请求日志与相关配置的指导,适用于安装配置 Nginx、设置自定义日志格式、实现限流、创建自定义错误页(404、500 等)以及让 Nginx 监听非标准端口的任务。

主要能力包括:在 http 块中定义 log_format 与 limit_req_zone,在 server/location 中应用 limit_req 与 access_log;按目录结构放置配置(nginx.conf 放全局设置,conf.d/*.conf 放 server 块,错误页放在 server 或 location 中);并给出服务管理与验证方式。

使用前建议先分析现有配置,阅读 /etc/nginx/nginx.conf,检查 include 指令,确认限流区域与日志格式定义位置;检查 Nginx 是否安装(which nginx 或 nginx -v)、是否运行(pgrep nginx),以及目标端口是否被占用(ss -tlnp | grep <port>);修改前备份:cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak。

关键用法:限流区域示例 limit_req_zone $binary_remote_addr zone=zonename:10m rate=10r/s; 应用 limit_req zone=zonename burst=5 nodelay; 日志格式示例 log_format custom_format '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"'; 应用 access_log /var/log/nginx/custom_access.log custom_format; 启动或重载前务必执行 nginx -t。服务命令因环境而不同:systemd 用 systemctl start/reload/stop nginx,直连用 nginx、nginx -s reload、nginx -s stop。

验证时可用 curl 检查状态码与错误页;限流需并发请求才能触发,例如 seq 20 | xargs -P 20 -I {} curl -s -o /dev/null -w "%{http_code}\n" http://localhost:<port>/;日志用 tail -f 查看。常见限制与问题:日志格式必须在 nginx.conf 中先定义再被 server 引用;顺序请求不会触发限流;配置语法错误须先 nginx -t;端口占用需先检查;容器或精简环境可能没有 systemctl;新配置需删除或禁用默认站点(rm -f /etc/nginx/sites-enabled/default)。