AI guide
# NGINX完全指南:实现高性能负载均衡的进阶实操指南
## 【One-Line Pitch】
A practical, recipe-driven guide to mastering NGINX as a load balancer, reverse proxy, and application delivery platform—covering everything from basic HTTP/TCP/UDP balancing to advanced security, automation, and NGINX Plus features. Ideal for DevOps engineers, site reliability engineers, and architects working with modern web architectures who need proven solutions they can implement immediately.
## 【Book Arc】
- **Opening (~0%–10%)**: Introduces NGINX's role in modern web infrastructure, covering installation, key files and directories (/etc/nginx/, nginx.conf, conf.d/), essential commands, and the foundational distinction between the http (Layer 7) and stream (Layer 4) contexts. Establishes the mental model for everything that follows.
- **Early (~10%–20%)**: Dives deep into high-performance load balancing—HTTP, TCP, and UDP upstream pools, weighted round-robin, least connections, generic hash, and IP hash algorithms. Covers session persistence (sticky routing) and health checks, including NGINX Plus's active health checks and slow-start features.
- **Early–Middle (~20%–37%)**: Explores traffic management (A/B testing with split_clients, GeoIP-based routing, connection/rate/bandwidth limiting) and scalable content caching (cache zones, hash keys, locking, stale cache, purging, slicing). Introduces programmability and automation: NGINX Plus API, key-value stores, the njs module for JavaScript extensions, and configuration management tools (Ansible, Chef, Consul templates).
- **Middle (~37%–50%)**: Focuses on authentication and security—HTTP basic auth, auth subrequests, JWT validation (NGINX Plus), OpenID Connect integration, CORS handling, client-side and upstream TLS encryption, secure links with expiring URLs, and HSTS enforcement.
- **Late (~50%–100%)**: Covers advanced security controls (country-based access restrictions), deployment to major cloud platforms (AWS, Google Cloud, Azure), NGINX Plus SAML service provider configuration, and modern features like HTTP/3 (QUIC), OpenTelemetry integration, and the njs module. Concludes with debugging, logging, request tracing, and performance tuning.
## 【Key Takeaways】
- **The http vs. stream context distinction is foundational** (Early): http operates at Layer 7 with full HTTP protocol awareness, while stream operates at Layer 4 for TCP/UDP routing. Choosing the right context determines what load-balancing and inspection capabilities you have.
- **Multiple load-balancing algorithms exist for different traffic patterns** (Early): Round-robin (default), weighted round-robin, least connections, generic hash, and random algorithms each suit different scenarios. Generic hash (e.g., using $remote_addr) works in both http and stream contexts, while IP hash is http-only.
- **Session persistence requires intelligent routing** (Early): For stateful applications, NGINX provides cookie-based and route-based sticky routing (NGINX Plus) to ensure subsequent requests reach the same backend server—critical for user experience in interactive applications.
- **Traffic management features are composable** (Early): split_clients enables A/B testing, GeoIP modules enable location-based routing, and limit_conn/limit_rate/limit_rate_after enable connection, rate, and bandwidth control. These can be mixed to create sophisticated traffic policies.
- **Cache keys determine cache effectiveness** (Early): The default proxy_cache_key ($scheme$proxy_host$request_uri) works for static content, but dynamic content requires custom keys incorporating user-specific variables like cookies—choosing the right key requires deep application knowledge.
- **NGINX Plus API enables dynamic infrastructure automation** (Middle): The REST API allows servers to self-register and deregister from upstream pools without manual intervention, enabling automatic scaling. The key-value store extends this to dynamic traffic management decisions like blocklists.
- **JWT validation and OIDC integration shift auth to the edge** (Middle): NGINX Plus can validate JWT signatures before requests reach application servers, and act as an OIDC relying party—reducing backend workload and centralizing security. Key management (rotation, secure storage) is critical.
- **Security headers and upstream encryption are non-negotiable** (Middle): HSTS prevents downgrade attacks, proxy_ssl_verify enables upstream certificate validation (off by default!), and secure_link provides expiring, user-specific protected URLs with proper HTTP 403/410 semantics.
## 【Reading Tips】
- **Skim the first chapter** if you're already familiar with NGINX basics—the file/directory layout and commands are standard, but the http vs. stream distinction is worth re-reading before Chapter 2.
- **Deep-read Chapters 2–3** for load balancing and traffic management—these are the core value of the book. Pay special attention to the algorithm selection guidance and how to combine rate/connection/bandwidth limits.
- **Chapter 5 (Programmability and Automation)** contains OCR-heavy code samples; focus on understanding the concepts (API-driven scaling, key-value stores, njs) rather than copying code verbatim. The njs JWT example is particularly useful but requires careful reading.
- **Chapter 7 (Security)** is where production-readiness lives—the upstream SSL verification defaults (off!) and secure_link patterns are easy to miss but critical for real deployments. The CORS and HSTS sections are practical and immediately applicable.
- **The NGINX Plus sections** (sticky routing, active health checks, API, JWT, OIDC, SAML) are clearly marked—if you're using open-source NGINX only, you can skim these but should still understand what features exist for future planning.
## 【Coverage Limits】
This guide covers the book's first ~50% in depth (load balancing, traffic management, caching, automation, authentication, and core security). The later chapters on cloud deployment, SAML, HTTP/3, OpenTelemetry, logging, and performance tuning are only briefly noted—the excerpts provide limited detail on these sections.
##
Passage locations
Page 11
...................................................................... 167 15.0 简介 167 15.1 使用压测工具实现测试自动化 167 15.2 控制浏览器缓存 168 15.3 保持客户端长连接 169 15.4 保持上游长连接...
View in text
Excerpt 2
t-Type 值定义为 'text/html',同时定义了响应正文中的字符串 "Welcome to nginx!"。HTTP match 代码块具有三个指令:status、header 和 body。这三个指令均 带有比较标记。 TCP/UDP 服务的 stream 健康检查非常相似: stream { s t...
View in text
Excerpt 3
务未提供类型(比如 AWS Cognito),因为此类服 务会更改分割数或完全删除它,以便 jwt 函数仅接收令牌值。 在 NGINX 核心配置中加载 njs 模块。在 http 代码块中导入并使用 JavaScript: 52 | 第 5 章:可编程性和自动化 该解决方案演示了 NGINX 中可用的 Lua 和...
View in text
Excerpt 4
add_header 'Content-Type' 'text/plain; charset=UTF-8'; add_header 'Content-Length' 0; return 204; } } } 这个示例中的内容很多,但通过使用 map 将 GET 和 POST 方法进行分组,简化了示例 中的内容。O...
View in text