[{"data":1,"prerenderedAt":63},["ShallowReactive",2],{"article-139":3},{"code":4,"msg":5,"data":6,"count":14},200,"查询成功",{"id":7,"title":8,"keywords":9,"description":10,"category_id":11,"content":12,"body_html":13,"thumb_up":14,"clicks":15,"sort":14,"remark":13,"status":16,"is_open":16,"is_deleted":14,"is_top":16,"is_recommend":16,"create_time":17,"update_time":18,"image_id":19,"url":13,"member_id":14,"cate_name":20,"prev":21,"next":24,"tags":27,"words":39,"read_time":40,"comments":14,"cover":41,"relevant":42},139,"Nginx 性能优化实战指南：从基础配置到高并发压测","Nginx性能优化, 缓存策略, 负载均衡, HTTPS配置, 限流防爬虫","Nginx 是全球使用最广泛的 Web 服务器之一，以高性能、低资源占用著称。但默认配置往往保守，没有发挥出 Nginx 的全部潜力。本文系统梳理 2025 年 Nginx 性能优化的核心配置项，从基础参数调优、Gzip 压缩、缓存策略、安全防护到压测验证，配合完整配置示例，帮你将网站性能提升数倍。",12,"## 一、基础配置优化：压榨硬件性能\n\n### 1.1 worker 进程配置\n\nNginx 启动后由一个 Master 进程管理一群 Worker 进程。Worker 进程才是真正处理请求的地方，Master 只负责管理。\n\n```nginx\n# \u002Fetc\u002Fnginx\u002Fnginx.conf\n\n# 全局块\nuser  nginx;\nworker_processes  auto;        # ✅ 自动匹配 CPU 核心数（推荐）\nworker_cpu_affinity auto;       # ✅ 将 worker 绑定到对应 CPU，减少上下文切换\nworker_priority  -5;            # 提高调度优先级（负数越高优先）\nworker_rlimit_nofile 65535;     # 每个 worker 能打开的文件描述符数量\n\n# 错误日志\nerror_log  \u002Fvar\u002Flog\u002Fnginx\u002Ferror.log warn;\n\n# PID 文件\npid        \u002Fvar\u002Frun\u002Fnginx.pid;\n\nevents {\n    worker_connections  10240;   # 每个 worker 最大并发连接数\n    use                  epoll;  # ✅ Linux 高效 I\u002FO 事件模型（生产环境必须）\n    multi_accept         on;     # ✅ 一次接受多个新连接\n}\n```\n\n**关键参数解读：**\n\n| 参数 | 默认值 | 推荐值 | 说明 |\n|------|--------|--------|------|\n| `worker_processes` | 1 | `auto` | 自动等于 CPU 核心数 |\n| `worker_connections` | 512 | 10240+ | 单进程最大并发数 |\n| `worker_rlimit_nofile` | — | 65535 | 文件描述符上限，需配合系统 `ulimit -n` |\n| `multi_accept` | off | on | 一次接收多个连接，减少 accept() 调用 |\n| `use epoll` | — | epoll | Linux 下最高效的事件模型 |\n\n**系统层文件描述符限制：**\n\n```bash\n# 查看当前限制\nulimit -n\n\n# 临时生效（重启失效）\nulimit -n 100000\n\n# 永久生效：编辑 \u002Fetc\u002Fsecurity\u002Flimits.conf\nnginx  soft  nofile  100000\nnginx  hard  nofile  100000\n\n# 编辑 \u002Fetc\u002Fsysctl.conf\necho \"fs.file-max = 2097152\" >> \u002Fetc\u002Fsysctl.conf\nsysctl -p\n```\n\n### 1.2 HTTP 连接与传输优化\n\n```nginx\nhttp {\n    include       \u002Fetc\u002Fnginx\u002Fmime.types;\n    default_type  application\u002Foctet-stream;\n\n    # ── 传输效率优化 ──────────────────────────────\n\n    sendfile         on;      # ✅ 启用零拷贝：文件从磁盘直发网络，不走用户态\n    tcp_nopush       on;      # ✅ sendfile 开启时：等凑满一个数据包再发，减少小包数量\n    tcp_nodelay      on;      # ✅ 禁用 Nagle 算法，小数据包立即发送（适合实时响应）\n    aio             on;      # ✅ 异步 I\u002FO，配合 directio 使用（大文件场景）\n    directio        512;      # 超过 512KB 的文件用 directio 跳过系统缓存（Linux）\n    open_file_cache max=10000 inactive=60s;  # 缓存文件元数据，减少 stat() 系统调用\n    open_file_cache_valid    30s;            # 元数据缓存有效期\n    open_file_cache_min_use  5;             # 访问 5 次后才缓存\n\n    # ── 连接超时优化 ──────────────────────────────\n\n    keepalive_timeout  65;      # 客户端保持连接时长（65秒）\n    keepalive_requests 10000;   # 单连接最大请求数，防止长连接滥用\n    client_header_timeout  10s; # 读取请求头超时\n    client_body_timeout   10s; # 读取请求体超时\n    send_timeout         10s;  # 发送给客户端超时\n    reset_timedout_connection on;  # 连接关闭时立即释放内存\n\n    # ── 请求体与请求头限制 ──────────────────────────\n\n    client_max_body_size      50m;  # 最大请求体（上传文件）\n    client_header_buffer_size  4k;   # 请求头缓冲区\n    large_client_header_buffers 4 32k;  # 大请求头（JWT\u002F长 Cookie 场景）\n}\n```\n\n**零拷贝原理说明：**\n\n```\n传统模式（sendfile off）：\n  磁盘 → 内核缓冲区 → 用户缓冲区 → Socket缓冲区 → 网卡\n  （4 次数据拷贝 + 2 次上下文切换）\n\n零拷贝模式（sendfile on）：\n  磁盘 → 内核缓冲区 → Socket缓冲区 → 网卡\n  （2 次数据拷贝 + 0 次上下文切换）\n```\n\n---\n\n## 二、Gzip 压缩：减少 60%-80% 传输量\n\n### 2.1 Gzip 基础配置\n\n```nginx\nhttp {\n    gzip                on;      # ✅ 启用 Gzip 压缩\n    gzip_vary           on;      # ✅ 根据 Accept-Encoding 缓存不同版本\n    gzip_proxied       any;      # 代理请求也压缩（即使后端已压缩）\n    gzip_disable       \"msie6\";  # IE6 不支持，禁用\n\n    # 压缩级别（1-9，默认 4）\n    # 级别越高压缩率越高，但 CPU 开销越大\n    # CDN\u002F中转节点：4-5；自有服务器：5-6；静态资源密集型：6\n    gzip_comp_level     5;\n\n    # 最小压缩阈值：小于此大小的文件不压缩（避免浪费 CPU）\n    gzip_min_length    1024;\n\n    # ✅ 压缩的文件 MIME 类型\n    gzip_types\n        text\u002Fplain\n        text\u002Fcss\n        text\u002Fjavascript\n        application\u002Fjavascript\n        application\u002Fjson\n        application\u002Fxml\n        application\u002Fxml+rss\n        application\u002Fx-javascript\n        application\u002Fx-font-ttf\n        application\u002Fx-web-app-manifest+json\n        font\u002Fopentype\n        font\u002Fttf\n        font\u002Feot\n        font\u002Fotf\n        image\u002Fsvg+xml\n        image\u002Fx-icon;\n}\n```\n\n### 2.2 Gzip 压缩效果实测\n\n```bash\n# 未压缩时的响应\ncurl -I -H \"Accept-Encoding: gzip\" https:\u002F\u002Fexample.com\u002Fapi\u002Fdata.json\n# Content-Length: 524288   (512KB)\n\n# 启用 Gzip 后（压缩率约 5）\ncurl -I -H \"Accept-Encoding: gzip\" https:\u002F\u002Fexample.com\u002Fapi\u002Fdata.json\n# Content-Length: 81920     (80KB)\n# 节省约 84% 带宽\n```\n\n### 2.3 Brotli 压缩（更优选择）\n\nBrotli 是 Google 推出的新一代压缩算法，同等压缩级别下比 Gzip 小 15%-25%：\n\n```nginx\nhttp {\n    # 需要安装 nginx-module-brotli\n    load_module modules\u002Fngx_http_brotli_filter_module.so;\n    load_module modules\u002Fngx_http_brotli_static_module.so;\n\n    brotli             on;\n    brotli_comp_level  6;      # Brotli 压缩级别（1-11）\n    brotli_types\n        text\u002Fplain\n        text\u002Fcss\n        application\u002Fjavascript\n        application\u002Fjson\n        application\u002Fxml\n        image\u002Fsvg+xml\n        font\u002Fttf\n        font\u002Fotf\n        font\u002Feot;\n}\n```\n\n---\n\n## 三、缓存策略：让静态资源\"永不过期\"\n\n### 3.1 浏览器缓存配置\n\n```nginx\nserver {\n    listen 80;\n    server_name example.com;\n\n    root \u002Fvar\u002Fwww\u002Fhtml;\n\n    # ── 静态资源缓存（永不过期 + 版本化）──────────────\n    location ~* \\.(css|js|jpg|jpeg|png|gif|ico|svg|woff|woff2|ttf|eot)$ {\n        expires         1y;                    # 缓存 1 年\n        add_header      Cache-Control \"public, immutable\";  # immutable：URL 不变则永不变\n        add_header      X-Cache-Status $upstream_cache_status;  # HIT\u002FMISS 调试用\n        access_log      off;                    # 静态资源关闭日志，省 I\u002FO\n    }\n\n    # ── HTML 文件（始终经过后端，确保最新）────────────\n    location ~* \\.html$ {\n        expires         -1;                     # 不缓存，每次请求最新\n        add_header      Cache-Control \"no-cache, no-store, must-revalidate\";\n    }\n}\n```\n\n### 3.2 代理缓存（反向代理缓存）\n\n```nginx\nhttp {\n    # ── 代理缓存配置 ──────────────────────────────\n    proxy_cache_path  \u002Fvar\u002Fcache\u002Fnginx levels=1:2\n                     keys_zone=api_cache:100m\n                     max_size=10g\n                     inactive=60m\n                     use_temp_path=off;\n\n    # ── API 缓存策略 ─────────────────────────────\n    upstream backend {\n        server 127.0.0.1:8080;\n        keepalive 32;  # 与后端保持长连接，减少建连开销\n    }\n\n    server {\n        listen 80;\n        server_name api.example.com;\n\n        # ✅ 缓存 GET\u002FHEAD 请求（POST\u002FPUT 等写操作不缓存）\n        proxy_cache_lock        on;         # 防止缓存击穿\n        proxy_cache_lock_timeout 5s;\n        proxy_cache_use_stale  error timeout updating http_500 http_502 http_503;\n        proxy_cache_background_update on;     # 后台更新缓存，用户无感知\n        proxy_cache_valid       200 60s;     # 200 响应缓存 60 秒\n        proxy_cache_valid       404 1m;      # 404 缓存 1 分钟\n        proxy_cache_key         \"$scheme$request_method$host$request_uri$http_x_custom\";  # 含自定义 header 区分用户\n        add_header              X-Cache-Status $upstream_cache_status;\n\n        location \u002Fapi\u002F {\n            proxy_pass         http:\u002F\u002Fbackend;\n            proxy_cache        api_cache;\n            # 缓存清理：缓存失效时立即回源，不等 inactive 时间\n            proxy_cache_purge  PURGE from 127.0.0.1;\n        }\n    }\n}\n```\n\n### 3.3 FastCGI 缓存（PHP 应用）\n\n```nginx\nhttp {\n    # FastCGI 缓存配置\n    fastcgi_cache_path \u002Fvar\u002Fcache\u002Fnginx\u002Ffcgi levels=1:2\n                       keys_zone=fcgi_cache:100m\n                       max_size=5g\n                       inactive=2h;\n\n    server {\n        listen 80;\n        server_name www.example.com;\n\n        # 绕过缓存的条件\n        set $skip_cache 0;\n        if ($request_uri ~* \"\u002Fadmin|\u002Flogin|\u002Fcart\") {\n            set $skip_cache 1;  # 管理后台\u002F登录\u002F购物车不缓存\n        }\n        if ($http_cookie ~* \"wordpress_logged_in\") {\n            set $skip_cache 1;  # 登录用户不缓存\n        }\n\n        location ~ \\.php$ {\n            fastcgi_pass    127.0.0.1:9000;\n            fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;\n            include         fastcgi_params;\n\n            # 缓存控制\n            fastcgi_cache              fcgi_cache;\n            fastcgi_cache_valid       200 10m;\n            fastcgi_cache_valid       404 1m;\n            fastcgi_cache_bypass     $skip_cache;\n            fastcgi_no_cache         $skip_cache;\n            fastcgi_cache_lock        on;\n            fastcgi_cache_lock_timeout 5s;\n            add_header               X-FastCGI-Cache $upstream_cache_status;\n        }\n    }\n}\n```\n\n---\n\n## 四、负载均衡与高可用\n\n### 4.1 常用负载均衡策略\n\n```nginx\nupstream backend_servers {\n    # ── 轮询（默认）：每台机器轮流处理 ───────────\n    # server 10.0.0.11:8080;\n    # server 10.0.0.12:8080;\n    # server 10.0.0.13:8080 down;  # down 表示永久剔除\n\n    # ── 加权轮询：权重越高，分到的请求越多 ─────────\n    server 10.0.0.11:8080 weight=5;\n    server 10.0.0.12:8080 weight=3;\n    server 10.0.0.13:8080 weight=2 backup;  # backup：仅所有非 backup 节点 down 时启用\n\n    # ── IP 哈希：同一 IP 始终路由到同一后端（适合有状态的场景）\n    # ip_hash;\n\n    # ── 最少连接：优先分配给连接数最少的节点 ───────\n    least_conn;\n\n    # 长连接复用：减少与后端的建连次数\n    keepalive 32;\n}\n\nserver {\n    listen 80;\n    server_name example.com;\n\n    location \u002F {\n        proxy_pass         http:\u002F\u002Fbackend_servers;\n        proxy_set_header   Host              $host;\n        proxy_set_header   X-Real-IP         $remote_addr;\n        proxy_set_header   X-Forwarded-For   $proxy_add_x_forwarded_for;\n        proxy_set_header   X-Forwarded-Proto $scheme;\n\n        # 健康检查\n        proxy_connect_timeout  5s;\n        proxy_read_timeout    30s;\n        proxy_next_upstream  error timeout http_502 http_503;  # 失败自动切到下一台\n    }\n}\n```\n\n### 4.2 健康检查配置\n\n```nginx\nupstream backend {\n    server 10.0.0.11:8080 max_fails=3 fail_timeout=30s;  # 30秒内失败3次则摘除\n    server 10.0.0.12:8080 max_fails=3 fail_timeout=30s;\n}\n```\n\n---\n\n## 五、安全防护配置\n\n### 5.1 隐藏版本号与敏感信息\n\n```nginx\nserver {\n    server_tokens off;      # ✅ 关闭 Server 头显示 Nginx 版本号\n    add_header  X-Frame-Options       \"SAMEORIGIN\"      always;\n    add_header  X-Content-Type-Options \"nosniff\"        always;\n    add_header  X-XSS-Protection      \"1; mode=block\"   always;\n    add_header  Referrer-Policy       \"no-referrer-when-downgrade\" always;\n    add_header  Permissions-Policy    \"geolocation=(), microphone=(), camera=()\" always;\n\n    # 自定义 Server 头（迷惑扫描器）\n    add_header  Server \"Apache\u002F2.4.41\" always;\n}\n```\n\n### 5.2 防盗链配置\n\n```nginx\nserver {\n    server_name example.com;\n\n    # 允许访问的域名白名单\n    valid_referers none blocked ~\\.google\\. ~\\.baidu\\. example.com *.example.com;\n\n    if ($invalid_referer) {\n        return   403;\n        # 或者重定向到一张警告图片\n        # rewrite ^\u002F.*$ \u002Fstatic\u002Fhotlink.jpg break;\n    }\n\n    location \u002Fuploads\u002F {\n        valid_referers ~\\.google\\. ~\\.baidu\\. example.com;\n        if ($invalid_referer) {\n            return 403;\n        }\n    }\n}\n```\n\n### 5.3 限流防护\n\n```nginx\nhttp {\n    # ── 连接数限制 ───────────────────────────────\n    # 基于 IP 的并发连接数限制\n    limit_conn_zone $binary_remote_addr zone=conn_limit:10m;\n\n    # ── 请求速率限制 ───────────────────────────────\n    # 每个 IP 每秒最多 10 个请求（令牌桶算法）\n    limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r\u002Fs;\n\n    server {\n        listen 80;\n        server_name example.com;\n\n        # 连接数限制：每个 IP 同时最多 5 个连接\n        limit_conn conn_limit 5;\n\n        # 请求速率限制：突发最多 20 个请求，超出的返回 503\n        limit_req zone=req_limit burst=20 nodelay;\n\n        # 返回 429 代替默认的 503（更友好的限流提示）\n        limit_req_status  429;\n        limit_conn_status 429;\n\n        # 限制单个 IP 同时下载速度（bytes\u002Fs）\n        limit_rate_after 1m;   # 前 1MB 不限速\n        limit_rate 200k;       # 之后限速 200KB\u002Fs\n    }\n}\n```\n\n### 5.4 防爬虫与恶意请求\n\n```nginx\nserver {\n    listen 80;\n    server_name example.com;\n\n    # ── UA 黑名单 ───────────────────────────────\n    if ($http_user_agent ~* \"(AhrefsBot|SemrushBot|MJ12bot|scrapbot|Python-urllib)\") {\n        return 403;\n    }\n\n    # ── 禁止通过代理访问 ───────────────────────\n    if ($http_via ~* \".+\") {\n        return 403;\n    }\n\n    # ── 常见攻击路径拦截 ───────────────────────\n    location ~ \u002F\\.(git|svn|hg|env|config|bak)$ {\n        deny all;\n        access_log off;\n        log_not_found off;\n    }\n\n    # SQL 注入防护\n    if ($query_string ~* \"union.*select.*\\(\") {\n        return 403;\n    }\n\n    # XSS 防护\n    if ($query_string ~* \"\u003C.*>\") {\n        return 403;\n    }\n}\n```\n\n---\n\n## 六、HTTPS 与 HTTP\u002F2 优化\n\n### 6.1 SSL\u002FTLS 配置\n\n```nginx\nserver {\n    listen 443 ssl http2;  # ✅ HTTP\u002F2 配合 HTTPS 使用\n    server_name example.com;\n\n    # ── SSL 证书配置 ────────────────────────────\n    ssl_certificate     \u002Fetc\u002Fnginx\u002Fssl\u002Fexample.com.crt;\n    ssl_certificate_key \u002Fetc\u002Fnginx\u002Fssl\u002Fexample.com.key;\n\n    # ── TLS 版本控制（禁用老旧协议）───────────────\n    ssl_protocols TLSv1.2 TLSv1.3;  # ✅ 只启用 TLS 1.2 和 1.3\n\n    # ── 加密套件（优先高性能 + 高安全）─────────────\n    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;\n\n    ssl_prefer_server_ciphers on;    # 服务端套件优先级高于客户端\n\n    # ── SSL 会话复用 ─────────────────────────────\n    ssl_session_cache   shared:SSL:50m;    # 50MB 缓存，减少握手开销\n    ssl_session_timeout 1d;             # 缓存有效期 1 天\n    ssl_session_tickets on;             # 支持会话票据（无状态恢复）\n\n    # ── OCSP Stapling（减少证书验证延迟）──────────\n    ssl_stapling on;\n    ssl_stapling_verify on;\n    resolver 8.8.8.8 8.8.4.4 valid=300s;\n    resolver_timeout 5s;\n}\n```\n\n### 6.2 HTTP\u002F2 与多路复用\n\n```nginx\n# HTTP\u002F2 的核心优势：\n# 1. 多路复用：一个连接并行处理多个请求（无需排队）\n# 2. Header 压缩（HPACK）：减少头部冗余\n# 3. 服务端推送：主动推送 CSS\u002FJS 等资源\n# 4. 流量控制：按优先级分配带宽\n\nserver {\n    listen 443 ssl http2;\n    server_name example.com;\n\n    # 服务端推送示例（推送关键 CSS\u002FJS）\n    location = \u002Findex.html {\n        http2_push \u002Fstatic\u002Fcss\u002Fmain.css;\n        http2_push \u002Fstatic\u002Fjs\u002Fapp.js;\n        http2_push \u002Fstatic\u002Ffonts\u002Ficon.woff2;\n    }\n}\n```\n\n---\n\n## 七、压测与监控：用数据验证优化效果\n\n### 7.1 压测工具：wrk\n\n```bash\n# 安装 wrk（Linux\u002FmacOS）\n# Ubuntu: apt install wrk\n# macOS:  brew install wrk\n\n# ── 基础压测：静态文件 ─────────────────────────\nwrk -t12 -c400 -d30s http:\u002F\u002F127.0.0.1\u002Findex.html\n# -t12 : 12 个线程\n# -c400: 400 个并发连接\n# -d30s: 持续 30 秒\n\n# 输出示例：\n# Running 30s test @ http:\u002F\u002F127.0.0.1\u002Findex.html\n# Thread Stats   Avg      Stdev     Max   +\u002F- Stdev\n# Latency       12.34ms    5.67ms  89.23ms   85.32%\n# Req\u002FSec       3205.56    234.12  4200.00     68.21%\n# 356234 requests in 30.01s, 4.28GB read\n# Socket errors: connect 0, read 0, write 0, timeout 0\n# Requests\u002Fsec:  11872.34    ← 关键指标：QPS\n# Transfer\u002Fsec: 146.12MB\n\n# ── 带 Lua 脚本的压测：模拟真实用户行为 ─────────\n# post.lua：每个请求带上随机用户 ID\nwrk -t8 -c200 -d60s -s post.lua http:\u002F\u002F127.0.0.1\u002Fapi\u002Fusers\n```\n\n**post.lua 示例：**\n\n```lua\n-- post.lua：POST 请求压测脚本\nwrk.method = \"POST\"\nwrk.headers[\"Content-Type\"] = \"application\u002Fjson\"\nwrk.body   = '{\"username\":\"user123\",\"action\":\"login\"}'\n```\n\n### 7.2 Nginx 内置状态监控\n\n```nginx\nhttp {\n    # 启用 status 监控模块\n    server {\n        listen 80;\n        server_name localhost;\n        location \u002Fnginx_status {\n            stub_status on;      # ✅ 开启状态监控\n            access_log   off;\n            allow        127.0.0.1;  # 仅本地访问\n            deny         all;\n        }\n    }\n}\n```\n\n```bash\n# 查看状态\ncurl http:\u002F\u002F127.0.0.1\u002Fnginx_status\n\n# Active connections: 291        ← 当前活跃连接数\n# server accepts handled requests\n#   16630948 16630948 31070465   ← 总接受数 \u002F 总连接数 \u002F 总请求数\n# Reading: 6 Writing: 179 Waiting: 106  ← 读\u002F写\u002F等待状态\n```\n\n### 7.3 优化前后对比（实测数据参考）\n\n以 4 核 CPU \u002F 8GB 内存服务器，100KB 静态资源为例：\n\n| 优化项 | 优化前 QPS | 优化后 QPS | 提升幅度 |\n|--------|-----------|-----------|---------|\n| 默认配置 | ~3,200 | — | 基准 |\n| + worker_processes auto + epoll | — | ~9,800 | **+206%** |\n| + sendfile + tcp_nopush + tcp_nodelay | — | ~14,500 | **+48%** |\n| + gzip 压缩（text\u002Fcss\u002Fjs） | — | ~28,000 | **+93%** |\n| + open_file_cache + expires 缓存 | — | ~45,000 | **+61%** |\n| **全部优化 + CDN 接入** | — | ~120,000+ | **+167%** |\n\n---\n\n## 八、生产环境完整配置模板\n\n```nginx\n# \u002Fetc\u002Fnginx\u002Fnginx.conf\nuser  nginx;\nworker_processes  auto;\nworker_cpu_affinity auto;\nworker_priority  -5;\nworker_rlimit_nofile 65535;\nerror_log  \u002Fvar\u002Flog\u002Fnginx\u002Ferror.log warn;\npid        \u002Fvar\u002Frun\u002Fnginx.pid;\n\nevents {\n    worker_connections  10240;\n    use                 epoll;\n    multi_accept        on;\n}\n\nhttp {\n    include       \u002Fetc\u002Fnginx\u002Fmime.types;\n    default_type  application\u002Foctet-stream;\n\n    # 传输优化\n    sendfile            on;\n    tcp_nopush          on;\n    tcp_nodelay         on;\n    aio                 on;\n    directio            512;\n    open_file_cache     max=10000 inactive=60s;\n    open_file_cache_valid 30s;\n\n    # 连接与超时\n    keepalive_timeout   65;\n    keepalive_requests  10000;\n    client_header_timeout  10s;\n    client_body_timeout    10s;\n    send_timeout           10s;\n    reset_timedout_connection on;\n\n    # 请求限制\n    client_max_body_size 50m;\n    client_header_buffer_size 4k;\n    large_client_header_buffers 4 32k;\n\n    # Gzip 压缩\n    gzip                on;\n    gzip_vary           on;\n    gzip_proxied       any;\n    gzip_comp_level     5;\n    gzip_min_length    1024;\n    gzip_types text\u002Fplain text\u002Fcss text\u002Fjavascript application\u002Fjavascript application\u002Fjson application\u002Fxml image\u002Fsvg+xml font\u002Fttf font\u002Fwoff;\n\n    # 安全头\n    server_tokens off;\n    add_header X-Frame-Options \"SAMEORIGIN\" always;\n    add_header X-Content-Type-Options \"nosniff\" always;\n    add_header X-XSS-Protection \"1; mode=block\" always;\n\n    # 限流\n    limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r\u002Fs;\n    limit_conn_zone $binary_remote_addr zone=conn_limit:10m;\n\n    # ── 上游服务器 ──────────────────────────────\n    upstream backend {\n        least_conn;\n        server 127.0.0.1:8080 weight=3;\n        server 127.0.0.1:8081 weight=2;\n        server 127.0.0.1:8082 weight=1 backup;\n        keepalive 32;\n    }\n\n    # ── 静态资源服务器 ───────────────────────────\n    server {\n        listen 80;\n        server_name static.example.com;\n\n        root \u002Fvar\u002Fwww\u002Fstatic;\n        index index.html;\n\n        # 静态资源永缓存\n        location ~* \\.(css|js|jpg|png|gif|ico|svg|woff|woff2|ttf|eot)$ {\n            expires 1y;\n            add_header Cache-Control \"public, immutable\";\n            access_log off;\n            gzip_static on;  # 优先使用预压缩文件\n        }\n\n        # HTML 不缓存\n        location ~* \\.html$ {\n            expires -1;\n        }\n    }\n\n    # ── API 反向代理 ────────────────────────────\n    server {\n        listen 80;\n        server_name api.example.com;\n\n        location \u002F {\n            proxy_pass         http:\u002F\u002Fbackend;\n            proxy_set_header   Host $host;\n            proxy_set_header   X-Real-IP $remote_addr;\n            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;\n\n            # 超时控制\n            proxy_connect_timeout  5s;\n            proxy_read_timeout     30s;\n            proxy_send_timeout     30s;\n\n            # 限流\n            limit_req zone=req_limit burst=20 nodelay;\n            limit_conn conn_limit 5;\n        }\n\n        # 健康检查接口\n        location \u002Fhealth {\n            access_log off;\n            return 200 \"OK\";\n        }\n    }\n}\n```\n\n---\n\n## 结语\n\nNginx 的性能优化是一个系统性工程，核心在于三点：**减少 I\u002FO**（零拷贝、缓存、压缩）、**减少连接开销**（长连接复用、worker 优化）、**精准控制流量**（限流、安全头、防盗链）。建议按以下路径推进：\n\n> **第一步**：检查当前 QPS 基线（wrk 压测）\n> **第二步**：按本文配置逐项优化，每次改完压测一次\n> **第三步**：观察 Nginx status 和慢查询日志，确认优化生效\n> **第四步**：接入 Prometheus + Grafana 持续监控，长期保持最优状态\n\n",null,0,30,1,"2026-04-12 04:07:34","2026-04-12 04:14:03",133,"Nginx",{"id":22,"title":23},138,"MySQL 高级用法完全指南：从窗口函数到性能调优的实战手册",{"id":25,"title":26},140,"一文讲透 Agent、RAG、Skill 与 MCP 的区别与联动",[28,30,33,36],{"id":29,"name":20},36,{"id":31,"name":32},117,"Web服务器",{"id":34,"name":35},118,"性能调优",{"id":37,"name":38},119," 运维实战",10512,26,"https:\u002F\u002Ftp.myong.top\u002Fstorage\u002Farticle\u002Fbe\u002F7eb81eb8c1826e0eb5671b64818cf3.jpg",[43,48,53,58],{"id":44,"title":45,"create_time":46,"description":47},71,"Nginx反爬虫策略，禁止某些UA抓取网站","2020-03-20 16:59:46","目前网络上的爬虫非常多，有对网站收录有益的，比如百度蜘蛛（Baiduspider），也有不但不遵守robots规则对服务器造成压力，还不能为网站带来流量的无用爬虫，为防止网站有可能会被别人爬，通过配置Nginx, 我们可以拦截大部分爬虫 ",{"id":49,"title":50,"create_time":51,"description":52},66,"Nginx解决访问图片显示404，403问题","2020-04-03 09:02:59","###### 问题描述\n\n项目中所有的资源放在`\u002Fwww\u002Fjianshu\u002Fpublic\u002Fstorage`中,希望通过url的方式将其展示出来，如下是配置\n\n```bash\neg: http:\u002F\u002Fdemo.test.com\u002Fstorage\u002Fimg\u002F1.png\n```\n\n```bash\nserver\n{\n    listen 80;\n    listen [::]:80;\n    server_name demo.test.com;\n    index index.php index.html in",{"id":54,"title":55,"create_time":56,"description":57},76,"Nginx配置优化","2019-12-29 14:37:11","\n###### 开启高效传输模式\n\n```bash\nhttp {\n\tinclude       mime.types;\n\t...\n\tdefault_type  application\u002Foctet-stream;\n\t...\n\tsendfile   on;\n\ttcp_nopush on;\n}\n#... 配置省略项\n```\n\n参数说明\n\n```bash\ninclude mime.types; #媒体类型,include 只是一个在当前文件中包含另一个文件内容的指令\ndefault_type appli",{"id":59,"title":60,"create_time":61,"description":62},60,"解决Nginx自动忽略header包含下划线参数方法","2019-07-05 15:14:57","该文章记录一次更换服务器后，web环境使用LNMP，部署项目时出现的问题以及解决方法，之前使用的LAMP环境。",1783431647408]