nginx-request-logging

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Nginx 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:
  1. Examine existing configuration structure
    • Read
      /etc/nginx/nginx.conf
      to understand the current setup
    • Check for existing
      include
      directives to understand file organization
    • Identify where log formats, rate limiting zones, and other global settings are defined
  2. Check system state
    • Verify if Nginx is already installed:
      which nginx
      or
      nginx -v
    • Check if Nginx is already running:
      pgrep nginx
      or
      ps aux | grep nginx
    • Verify if the target port is available:
      ss -tlnp | grep <port>
      or
      netstat -tlnp | grep <port>
  3. Backup original configuration
    • Create a backup before modifications:
      cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak
修改Nginx配置前,请完成以下步骤:
  1. 检查现有配置结构
    • 读取
      /etc/nginx/nginx.conf
      以了解当前配置
    • 检查现有的
      include
      指令以了解文件组织结构
    • 确定日志格式、速率限制区域及其他全局设置的定义位置
  2. 检查系统状态
    • 验证Nginx是否已安装:执行
      which nginx
      nginx -v
    • 检查Nginx是否正在运行:执行
      pgrep nginx
      ps aux | grep nginx
    • 验证目标端口是否可用:执行
      ss -tlnp | grep <port>
      netstat -tlnp | grep <port>
  3. 备份原始配置
    • 修改前创建备份:执行
      cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak

Configuration Approach

配置方法

Directory Structure

目录结构

Nginx configurations typically follow this hierarchy:
  • /etc/nginx/nginx.conf
    - Main configuration (global settings, log formats, rate limiting zones)
  • /etc/nginx/conf.d/
    - Site-specific configurations (server blocks)
  • /etc/nginx/sites-available/
    and
    /etc/nginx/sites-enabled/
    - Alternative site management (Debian-based)
Nginx配置通常遵循以下层级结构:
  • /etc/nginx/nginx.conf
    - 主配置文件(全局设置、日志格式、速率限制区域)
  • /etc/nginx/conf.d/
    - 站点特定配置(server块)
  • /etc/nginx/sites-available/
    /etc/nginx/sites-enabled/
    - 可选的站点管理方式(基于Debian系统)

Configuration Placement Guidelines

配置放置指南

Setting TypeLocationReason
Log format definitions
nginx.conf
(http block)
Must be defined before use in server blocks
Rate limiting zones
nginx.conf
(http block)
Zones are shared across server blocks
Server blocks
conf.d/*.conf
Modular, easy to manage
Custom error pagesServer block or location blockContext-specific
设置类型位置原因
日志格式定义
nginx.conf
(http块)
必须在server块引用之前定义
速率限制区域
nginx.conf
(http块)
区域可在多个server块之间共享
Server块
conf.d/*.conf
模块化设计,易于管理
自定义错误页面Server块或location块基于上下文生效

Rate Limiting Configuration

速率限制配置

Rate limiting requires two parts:
  1. Zone definition (in http block of nginx.conf):
    nginx
    limit_req_zone $binary_remote_addr zone=zonename:10m rate=10r/s;
  2. Zone application (in server or location block):
    nginx
    limit_req zone=zonename burst=5 nodelay;
速率限制配置分为两部分:
  1. 区域定义(在nginx.conf的http块中):
    nginx
    limit_req_zone $binary_remote_addr zone=zonename:10m rate=10r/s;
  2. 区域应用(在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:
EnvironmentStart CommandReload CommandStop Command
systemd
systemctl start nginx
systemctl reload nginx
systemctl stop nginx
Direct
nginx
nginx -s reload
nginx -s stop
Docker/Container
nginx -g 'daemon off;'
nginx -s reload
nginx -s quit
Important: Always test configuration before starting/reloading:
bash
nginx -t
Nginx服务管理方式因环境而异:
环境启动命令重载命令停止命令
systemd
systemctl start nginx
systemctl reload nginx
systemctl stop nginx
直接运行
nginx
nginx -s reload
nginx -s stop
Docker/容器
nginx -g 'daemon off;'
nginx -s reload
nginx -s quit
重要提示: 启动或重载前务必测试配置:
bash
nginx -t

Verification Strategies

验证策略

Basic Functionality

基础功能验证

bash
curl -s http://localhost:<port>/
curl -s -o /dev/null -w "%{http_code}" http://localhost:<port>/nonexistent
bash
curl -s http://localhost:<port>/
curl -s -o /dev/null -w "%{http_code}" http://localhost:<port>/nonexistent

Rate 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.log
bash
tail -f /var/log/nginx/access.log
tail -f /var/log/nginx/error.log

Common Pitfalls

常见陷阱

  1. Log format not found: Log format must be defined in nginx.conf before being referenced in server blocks
  2. Rate limiting not triggering: Sequential requests are too slow; use parallel requests with
    xargs -P
    or similar
  3. Configuration syntax errors: Always run
    nginx -t
    before starting or reloading
  4. Port already in use: Check with
    ss -tlnp
    before configuring a new port
  5. systemctl not available: In containers or minimal environments, use
    nginx
    command directly
  6. Default site conflicts: Remove or disable default site configuration when creating custom configurations:
    bash
    rm -f /etc/nginx/sites-enabled/default
  7. Missing directories: Verify required directories exist before writing configuration:
    bash
    ls -la /etc/nginx/conf.d/
  1. 日志格式未找到:日志格式必须在server块引用之前在nginx.conf中定义
  2. 速率限制未触发:顺序请求速度太慢;使用
    xargs -P
    或类似工具发起并行请求
  3. 配置语法错误:启动或重载前务必运行
    nginx -t
    检查
  4. 端口已被占用:配置新端口前先用
    ss -tlnp
    检查
  5. systemctl不可用:在容器或极简环境中,直接使用
    nginx
    命令
  6. 默认站点冲突:创建自定义配置时,移除或禁用默认站点配置:
    bash
    rm -f /etc/nginx/sites-enabled/default
  7. 目录缺失:编写配置前验证所需目录是否存在:
    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 -p
    ,
    rm -f
    to handle existing/missing files gracefully
  • 批量文件操作:尽可能并行创建多个静态文件(如index.html、404.html等)
  • 合并验证步骤:在一次验证过程中测试多个端点
  • 提前规划验证:在实施前确定测试策略
  • 使用幂等命令:优先使用
    mkdir -p
    rm -f
    等命令,以优雅处理文件存在或缺失的情况

Example Workflow

示例工作流

  1. Check system state (Nginx installed, running, port availability)
  2. Read existing nginx.conf structure
  3. Backup configuration
  4. Create required directories and static content
  5. Modify nginx.conf for global settings (log format, rate limiting zone)
  6. Create server configuration in conf.d/
  7. Remove conflicting default configurations
  8. Test configuration with
    nginx -t
  9. Start/reload Nginx service
  10. Verify all functionality (main page, error pages, rate limiting, logs)
  1. 检查系统状态(Nginx是否安装、运行状态、端口可用性)
  2. 读取现有nginx.conf结构
  3. 备份配置
  4. 创建所需目录和静态内容
  5. 修改nginx.conf配置全局设置(日志格式、速率限制区域)
  6. 在conf.d/中创建server配置
  7. 移除冲突的默认配置
  8. 使用
    nginx -t
    测试配置
  9. 启动/重载Nginx服务
  10. 验证所有功能(主页、错误页面、速率限制、日志)