nginx-request-logging
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseNginx Request Logging Configuration
Nginx请求日志配置
This skill provides guidance for configuring Nginx web servers with custom logging, rate limiting, and error handling.
本技能提供了为Nginx Web服务器配置自定义日志、速率限制和错误处理的指导。
When to Use This Skill
何时使用本技能
Apply this skill when tasks involve:
- Installing and configuring Nginx
- Setting up custom log formats
- Implementing rate limiting
- Creating custom error pages (404, 500, etc.)
- Configuring Nginx to listen on non-standard ports
当你需要处理以下任务时,可应用本技能:
- 安装和配置Nginx
- 设置自定义日志格式
- 实现速率限制
- 创建自定义错误页面(404、500等)
- 配置Nginx监听非标准端口
Pre-Configuration Analysis
配置前分析
Before modifying any Nginx configuration:
-
Examine existing configuration structure
- Read to understand the current setup
/etc/nginx/nginx.conf - Check for existing directives to understand file organization
include - Identify where log formats, rate limiting zones, and other global settings are defined
- Read
-
Check system state
- Verify if Nginx is already installed: or
which nginxnginx -v - Check if Nginx is already running: or
pgrep nginxps aux | grep nginx - Verify if the target port is available: or
ss -tlnp | grep <port>netstat -tlnp | grep <port>
- Verify if Nginx is already installed:
-
Backup original configuration
- Create a backup before modifications:
cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak
- Create a backup before modifications:
修改Nginx配置前,请完成以下步骤:
-
检查现有配置结构
- 读取以了解当前配置
/etc/nginx/nginx.conf - 检查现有的指令以了解文件组织结构
include - 确定日志格式、速率限制区域及其他全局设置的定义位置
- 读取
-
检查系统状态
- 验证Nginx是否已安装:执行或
which nginxnginx -v - 检查Nginx是否正在运行:执行或
pgrep nginxps aux | grep nginx - 验证目标端口是否可用:执行或
ss -tlnp | grep <port>netstat -tlnp | grep <port>
- 验证Nginx是否已安装:执行
-
备份原始配置
- 修改前创建备份:执行
cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak
- 修改前创建备份:执行
Configuration Approach
配置方法
Directory Structure
目录结构
Nginx configurations typically follow this hierarchy:
- - Main configuration (global settings, log formats, rate limiting zones)
/etc/nginx/nginx.conf - - Site-specific configurations (server blocks)
/etc/nginx/conf.d/ - and
/etc/nginx/sites-available/- Alternative site management (Debian-based)/etc/nginx/sites-enabled/
Nginx配置通常遵循以下层级结构:
- - 主配置文件(全局设置、日志格式、速率限制区域)
/etc/nginx/nginx.conf - - 站点特定配置(server块)
/etc/nginx/conf.d/ - 和
/etc/nginx/sites-available/- 可选的站点管理方式(基于Debian系统)/etc/nginx/sites-enabled/
Configuration Placement Guidelines
配置放置指南
| Setting Type | Location | Reason |
|---|---|---|
| Log format definitions | | Must be defined before use in server blocks |
| Rate limiting zones | | Zones are shared across server blocks |
| Server blocks | | Modular, easy to manage |
| Custom error pages | Server block or location block | Context-specific |
| 设置类型 | 位置 | 原因 |
|---|---|---|
| 日志格式定义 | | 必须在server块引用之前定义 |
| 速率限制区域 | | 区域可在多个server块之间共享 |
| Server块 | | 模块化设计,易于管理 |
| 自定义错误页面 | Server块或location块 | 基于上下文生效 |
Rate Limiting Configuration
速率限制配置
Rate limiting requires two parts:
-
Zone definition (in http block of nginx.conf):nginx
limit_req_zone $binary_remote_addr zone=zonename:10m rate=10r/s; -
Zone application (in server or location block):nginx
limit_req zone=zonename burst=5 nodelay;
速率限制配置分为两部分:
-
区域定义(在nginx.conf的http块中):nginx
limit_req_zone $binary_remote_addr zone=zonename:10m rate=10r/s; -
区域应用(在server或location块中):nginx
limit_req zone=zonename burst=5 nodelay;
Custom Log Format
自定义日志格式
Define custom log formats in the http block:
nginx
log_format custom_format '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';Apply in server block:
nginx
access_log /var/log/nginx/custom_access.log custom_format;在http块中定义自定义日志格式:
nginx
log_format custom_format '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';在server块中应用:
nginx
access_log /var/log/nginx/custom_access.log custom_format;Service Management
服务管理
Nginx service management varies by environment:
| Environment | Start Command | Reload Command | Stop Command |
|---|---|---|---|
| systemd | | | |
| Direct | | | |
| Docker/Container | | | |
Important: Always test configuration before starting/reloading:
bash
nginx -tNginx服务管理方式因环境而异:
| 环境 | 启动命令 | 重载命令 | 停止命令 |
|---|---|---|---|
| systemd | | | |
| 直接运行 | | | |
| Docker/容器 | | | |
重要提示: 启动或重载前务必测试配置:
bash
nginx -tVerification Strategies
验证策略
Basic Functionality
基础功能验证
bash
curl -s http://localhost:<port>/
curl -s -o /dev/null -w "%{http_code}" http://localhost:<port>/nonexistentbash
curl -s http://localhost:<port>/
curl -s -o /dev/null -w "%{http_code}" http://localhost:<port>/nonexistentRate Limiting Verification
速率限制验证
Rate limiting requires concurrent requests to trigger. Sequential requests will not exceed the rate limit.
Correct approach (parallel requests):
bash
seq 20 | xargs -P 20 -I {} curl -s -o /dev/null -w "%{http_code}\n" http://localhost:<port>/Incorrect approach (will not trigger rate limiting):
bash
for i in {1..20}; do curl -s http://localhost:<port>/; done # Too slow, sequential速率限制需要并发请求才能触发,顺序请求不会超出速率限制。
正确方法(并行请求):
bash
seq 20 | xargs -P 20 -I {} curl -s -o /dev/null -w "%{http_code}\n" http://localhost:<port>/错误方法(无法触发速率限制):
bash
for i in {1..20}; do curl -s http://localhost:<port>/; done # 速度过慢,为顺序请求Log Verification
日志验证
bash
tail -f /var/log/nginx/access.log
tail -f /var/log/nginx/error.logbash
tail -f /var/log/nginx/access.log
tail -f /var/log/nginx/error.logCommon Pitfalls
常见陷阱
-
Log format not found: Log format must be defined in nginx.conf before being referenced in server blocks
-
Rate limiting not triggering: Sequential requests are too slow; use parallel requests withor similar
xargs -P -
Configuration syntax errors: Always runbefore starting or reloading
nginx -t -
Port already in use: Check withbefore configuring a new port
ss -tlnp -
systemctl not available: In containers or minimal environments, usecommand directly
nginx -
Default site conflicts: Remove or disable default site configuration when creating custom configurations:bash
rm -f /etc/nginx/sites-enabled/default -
Missing directories: Verify required directories exist before writing configuration:bash
ls -la /etc/nginx/conf.d/
-
日志格式未找到:日志格式必须在server块引用之前在nginx.conf中定义
-
速率限制未触发:顺序请求速度太慢;使用或类似工具发起并行请求
xargs -P -
配置语法错误:启动或重载前务必运行检查
nginx -t -
端口已被占用:配置新端口前先用检查
ss -tlnp -
systemctl不可用:在容器或极简环境中,直接使用命令
nginx -
默认站点冲突:创建自定义配置时,移除或禁用默认站点配置:bash
rm -f /etc/nginx/sites-enabled/default -
目录缺失:编写配置前验证所需目录是否存在:bash
ls -la /etc/nginx/conf.d/
Execution Efficiency
执行效率
- Batch file operations: Create multiple static files (index.html, 404.html, etc.) in parallel when possible
- Combine verification steps: Test multiple endpoints in a single verification pass
- Plan verification upfront: Determine the testing strategy before implementation
- Use idempotent commands: Prefer ,
mkdir -pto handle existing/missing files gracefullyrm -f
- 批量文件操作:尽可能并行创建多个静态文件(如index.html、404.html等)
- 合并验证步骤:在一次验证过程中测试多个端点
- 提前规划验证:在实施前确定测试策略
- 使用幂等命令:优先使用、
mkdir -p等命令,以优雅处理文件存在或缺失的情况rm -f
Example Workflow
示例工作流
- Check system state (Nginx installed, running, port availability)
- Read existing nginx.conf structure
- Backup configuration
- Create required directories and static content
- Modify nginx.conf for global settings (log format, rate limiting zone)
- Create server configuration in conf.d/
- Remove conflicting default configurations
- Test configuration with
nginx -t - Start/reload Nginx service
- Verify all functionality (main page, error pages, rate limiting, logs)
- 检查系统状态(Nginx是否安装、运行状态、端口可用性)
- 读取现有nginx.conf结构
- 备份配置
- 创建所需目录和静态内容
- 修改nginx.conf配置全局设置(日志格式、速率限制区域)
- 在conf.d/中创建server配置
- 移除冲突的默认配置
- 使用测试配置
nginx -t - 启动/重载Nginx服务
- 验证所有功能(主页、错误页面、速率限制、日志)