什么是Nginx?集Web服务器、反向代理与负载均衡于一体
DevOps

什么是Nginx?集Web服务器、反向代理与负载均衡于一体

什么是Nginx?一款高性能Web服务器,同时兼具反向代理和负载均衡功能,每秒可处理数百万请求。了解其配置方式、实际应用场景,以及与Apache的对比分析。

系列文章: DevOps
  1. 1 API网关是什么?微服务的统一入口点
  2. 2 NAT是什么?计算机网络中的网络地址转换详解
  3. 3 GitLab CI/CD是什么?自动化构建、测试与部署流水线
  4. 4 Apache Kafka是什么?分布式事件流处理平台详解
  5. 5 Serverless是什么?FaaS、冷启动与何时选择无服务器架构
  6. 6 Subnet和CIDR是什么?IP网络分段与现代路由
  7. 7 什么是Kubernetes?当今最流行的容器编排平台
  8. 8 Proxy是什么?正向代理、反向代理与SOCKS5详解
  9. 9 什么是Nginx?集Web服务器、反向代理与负载均衡于一体
✦ 快速摘要
什么是Nginx?一款高性能Web服务器,同时兼具反向代理和负载均衡功能,每秒可处理数百万请求。了解其配置方式、实际应用场景,以及与Apache的对比分析。
这篇文章怎么样?

Nginx(读作"engine-x")诞生于2004年,最初是为了解决C10K问题——即Apache在当时难以高效处理的10,000个并发连接。如今,Nginx已成为全球最流行的Web服务器,运行于全球超过34%的网站,是大多数现代DevOps流水线的默认选择。

什么是Nginx?

Nginx 是一款多功能开源软件,可同时扮演多种角色:提供静态文件的Web服务器、将请求转发至后端的反向代理,以及在多台服务器间分配负载的负载均衡器。其异步事件驱动架构使单个worker进程无需创建新线程或进程即可同时处理数千个连接——这与Apache的thread-per-request模型截然不同。

可以将Nginx想象成办公楼的智能前台:来访者(HTTP请求)始终先经过前台,前台立即处理简单需求(如分发现成文件,即静态文件),对于复杂需求则引导访客到正确的部门(后端服务),而无需访客自行摸索前往楼上。

Nginx的三大核心角色

Web服务器——高速提供静态内容

Nginx以极低延迟直接从磁盘提供HTML、CSS、JavaScript、图片和视频。由于无需为每个文件创建新进程或线程,即使在普通硬件上,Nginx也能每秒处理数百万个请求。这正是CDN和静态托管服务(如Netlify、Vercel自建架构)通常在边缘节点使用Nginx的原因。

反向代理——保护后端的中间层

后端应用(Node.js、Python/Gunicorn、Go、PHP-FPM)前部署Nginx时,Nginx充当反向代理:接收来自互联网的所有请求,完成TLS终止(SSL termination),可选地缓存响应、启用gzip压缩,然后通过proxy_pass将请求转发给运行在localhost的后端。后端完全对外部互联网不可见。

负载均衡器——在多个实例间分配流量

当系统拥有多个后端实例(横向扩展)时,Nginx的upstream块充当第7层负载均衡器,按照round-robin、least_conn或ip_hash算法分配请求。这是实现微服务架构零停机部署的基础。

Nginx、Apache与IIS对比

Nginx vs Apache vs IIS 对比
Tested on 2026-06-12 Nginx 1.26 / Apache 2.4 / IIS 10
| 对比项 | Nginx | Apache | IIS | |---|---|---|---| | 架构 | 事件驱动(异步) | 每请求独立进程/线程 | 线程池(Windows) | | 高负载性能 | 非常高 | 中等 | 高(Windows) | | 配置方式 | nginx.conf,简洁 | httpd.conf + .htaccess | GUI + XML | | 动态模块 | 不支持(静态编译) | 支持(.so可加载) | 支持(IIS模块) | | SSL终止 | 优秀 | 优秀 | 优秀 | | 平台支持 | Linux/macOS/Windows | 跨平台 | 仅Windows | | 费用 | 免费(NGINX Plus:付费) | 免费 | 随Windows Server附带 | | 最适合 | 反向代理、静态内容、K8s Ingress | PHP传统应用、.htaccess灵活配置 | Microsoft技术栈(.NET、[IIS](/iis-zh/)) |
何时选择Apache而非Nginx?

如果应用大量依赖每目录.htaccess文件(共享托管、WordPress插件自动写入重写规则),Apache更为灵活,因为它会在每次请求时读取.htaccess。Nginx不支持.htaccess——所有配置必须集中写在nginx.conf文件中。

Nginx基础配置

以下是完整的nginx.conf配置文件,包含提供静态文件的server块、到后端的反向代理配置,以及上游负载均衡设置。

nginx
 1# /etc/nginx/nginx.conf
 2worker_processes auto;          # 自动选择worker数量 = CPU核心数
 3events {
 4    worker_connections 1024;    # 每个worker的最大连接数
 5}
 6
 7http {
 8    # --- Upstream: 用于负载均衡的后端池 ---
 9    upstream app_backend {
10        least_conn;             # 算法:优先选择连接数最少的服务器
11        server 10.0.0.10:8080 weight=3;
12        server 10.0.0.11:8080 weight=2;
13        server 10.0.0.12:8080 weight=1 max_fails=3 fail_timeout=30s;
14    }
15
16    # --- Server块:HTTPS + 反向代理 ---
17    server {
18        listen 443 ssl http2;
19        server_name example.com www.example.com;
20
21        ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
22        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
23        ssl_protocols       TLSv1.2 TLSv1.3;
24        ssl_ciphers         HIGH:!aNULL:!MD5;
25
26        # 直接提供静态文件(图片、CSS、JS)
27        location /static/ {
28            root /var/www/myapp;
29            expires 30d;
30            add_header Cache-Control "public, immutable";
31        }
32
33        # 将其余所有请求代理到后端池
34        location / {
35            proxy_pass         http://app_backend;
36            proxy_set_header   Host              $host;
37            proxy_set_header   X-Real-IP         $remote_addr;
38            proxy_set_header   X-Forwarded-For   $proxy_add_x_forwarded_for;
39            proxy_set_header   X-Forwarded-Proto $scheme;
40            proxy_connect_timeout 5s;
41            proxy_read_timeout    60s;
42        }
43    }
44
45    # --- HTTP → HTTPS 重定向 ---
46    server {
47        listen 80;
48        server_name example.com www.example.com;
49        return 301 https://$host$request_uri;
50    }
51}

重要指令说明

  • worker_processes auto — Nginx自动检测CPU核心数并启动相应数量的worker,最大化吞吐量。
  • upstream — 定义后端池;least_conn指令选择连接数最少的服务器,而非默认的round-robin。
  • proxy_set_header X-Real-IP — 将客户端真实IP传递给后端;否则后端只能看到Nginx的IP。
  • expires 30d — 为静态文件启用HTTP缓存,显著减轻服务器负载。

实际应用场景

提供静态网站 / JAMstack

Nginx只需几行location块即可提供Next.js、Hugo或任何静态站点生成器的完整构建目录。Nginx提供静态文件的速度接近磁盘/网络速度上限——应用层的任何框架都无法与之竞争。

后端应用反向代理

这是最常见的使用场景:Nginx监听公开的80/443端口,后端应用运行在localhost:3000或localhost:8080,无需对外暴露。Nginx负责处理TLS、gzip和慢速客户端连接——后端只需专注于业务逻辑。

SSL终止

无需在每个后端服务上单独安装TLS,将所有证书管理集中在Nginx处理。后端通过内部HTTP(专用局域网内的明文传输)与Nginx通信——简化了配置,并通过Certbot轻松实现证书续签。

限速——防止API滥用

nginx
 1http {
 2    limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
 3
 4    server {
 5        location /api/ {
 6            limit_req zone=api_limit burst=20 nodelay;
 7            proxy_pass http://app_backend;
 8        }
 9    }
10}

limit_req_zone指令按IP创建共享内存区,将请求限制为每秒10个,最大突发20个。超出阈值的请求直接在Nginx层收到HTTP 429响应,不消耗任何后端资源。

Nginx作为Kubernetes中的Ingress Controller

Kubernetes集群中,Nginx Ingress Controller 是将HTTP/HTTPS服务暴露到集群外部最常用的方式。YAML格式的Ingress资源将域名和路径映射到内部Service:

YAML
 1apiVersion: networking.k8s.io/v1
 2kind: Ingress
 3metadata:
 4  name: myapp-ingress
 5  annotations:
 6    nginx.ingress.kubernetes.io/rewrite-target: /
 7    nginx.ingress.kubernetes.io/limit-rps: "100"
 8spec:
 9  ingressClassName: nginx
10  tls:
11    - hosts:
12        - api.example.com
13      secretName: tls-secret
14  rules:
15    - host: api.example.com
16      http:
17        paths:
18          - path: /v1
19            pathType: Prefix
20            backend:
21              service:
22                name: api-v1-svc
23                port:
24                  number: 80
25          - path: /v2
26            pathType: Prefix
27            backend:
28              service:
29                name: api-v2-svc
30                port:
31                  number: 80

Nginx Ingress Controller读取Ingress资源并自动重新加载内部nginx.conf配置,无需重启Pod。这正是微服务系统实现滚动更新的方式:只需修改path规则,即可将流量从/v1逐步迁移到/v2

重新加载前先检查配置

在执行nginx -s reload之前,务必先运行nginx -t。该命令会检查整个nginx.conf及所有包含文件的语法,并在发现错误时返回具体提示。带有错误配置的重新加载会被自动拒绝——Nginx绝不会应用错误配置而导致服务中断。

Nginx性能优化

除基础配置外,以下几个常被忽视的指令对吞吐量有重大影响:

nginx
1http {
2    sendfile        on;       # 使用sendfile()系统调用——从磁盘到socket的零拷贝
3    tcp_nopush      on;       # 在发送前合并多个TCP段
4    tcp_nodelay     on;       # 为keep-alive连接禁用Nagle算法
5    keepalive_timeout 65;     # 保持TCP连接65秒(减少重复TLS握手)
6    gzip            on;
7    gzip_types      text/plain text/css application/json application/javascript;
8    gzip_min_length 1000;     # 不压缩小于1KB的文件(开销大于收益)
9}

sendfile on是提供大型静态文件时最重要的优化——内核直接将数据从页缓存传输到socket,无需经过用户空间复制。

结论: Nginx不仅仅是一款Web服务器——它是现代架构中全面的流量调度层。无论您是在提供静态SPA、为Node.js后端做代理、对微服务进行负载均衡,还是需要Kubernetes的Ingress Controller,Nginx都能以单一二进制文件提供一致、高性能且配置透明的解决方案。

参考资料

API Gateway是什么?微服务架构的入口

常见问题

常见问题Q&A
Nginx与Apache最重要的区别是什么?
Apache通过为每个请求分配独立的线程/进程(prefork/worker MPM)来处理请求,在高并发连接时会消耗大量内存。Nginx采用异步事件驱动架构——单个worker进程可同时处理数千个连接,内存占用极低。在高流量和大量空闲(keep-alive)连接的场景下,Nginx的性能优势十分明显。
什么是反向代理?为什么应该使用Nginx作为反向代理?
反向代理是位于内部服务器前端的中间服务器,接收客户端请求后转发给合适的后端服务器。使用Nginx作为反向代理可以隐藏后端地址、集中管理SSL终止、启用缓存和gzip压缩,同时保护应用免受直接攻击。
Nginx是如何实现负载均衡的?
Nginx通过upstream指令支持多种负载均衡算法:round-robin(默认轮询)、least_conn(最少连接数)、ip_hash(同一IP始终路由到同一服务器)和random(随机)。upstream块中的每台服务器都可设置weight和max_fails参数,以控制流量分配比例并自动从池中剔除故障服务器。
Nginx能替代应用服务器吗?
不建议这样做。Nginx无法直接运行Python、PHP或Node.js代码。Nginx的正确角色是:接收来自互联网的请求,立即提供静态文件,然后通过proxy_pass将其余请求转发给Gunicorn、PHP-FPM、Node.js进程或任何正在监听的应用服务器。这种组合能同时优化性能和安全性。
如何在Nginx上配置SSL/TLS?
在监听443端口的server块中,添加ssl_certificate指向.pem文件,ssl_certificate_key指向私钥文件。通过ssl_protocols启用TLS 1.2/1.3,通过ssl_ciphers选择强加密套件。使用listen 80配合return 301实现HTTP自动重定向到HTTPS。使用Let's Encrypt时,Certbot工具会自动写入这些指令。

Nginx (pronounced "engine-x") was created in 2004, originally to solve the C10K problem — serving 10,000 concurrent connections that Apache struggled with at the time. Today Nginx is the world's most popular web server, running on more than 34% of all websites globally and serving as the default choice for most modern DevOps pipelines.

What is Nginx?

Nginx is a versatile open-source software platform that functions simultaneously as: a web server for serving static files, a reverse proxy that forwards requests to backends, and a load balancer that distributes traffic across multiple servers. Its asynchronous, event-driven architecture allows a single worker process to handle thousands of connections at once without spawning new threads or processes — fundamentally different from Apache's thread-per-request model.

Think of Nginx as the intelligent front-desk receptionist of an office building: every visitor (HTTP request) always meets the receptionist first. The receptionist immediately handles simple requests like handing out available documents (static files), while more complex requests are routed to the right department (backend service) without the visitor having to find their own way.

Three core roles of Nginx

Web server — high-speed static content delivery

Nginx serves HTML, CSS, JavaScript, images, and video directly from disk with extremely low latency. Because it never needs to spawn a new process or thread per file, Nginx handles millions of requests per second even on modest hardware. This is why CDNs and static hosting platforms (Netlify, Vercel's own infrastructure) typically run Nginx at the edge layer.

Reverse proxy — a protective layer in front of your backend

When you place Nginx in front of a backend application (Node.js, Python/Gunicorn, Go, PHP-FPM), Nginx acts as a reverse proxy: it receives all requests from the internet, terminates TLS (SSL termination), optionally caches responses and applies gzip compression, then forwards traffic via proxy_pass to the backend running on localhost. The backend is completely shielded from the public internet.

Load balancer — distributing traffic across multiple instances

When your system runs multiple backend instances (scaled out horizontally), the Nginx upstream block acts as a Layer 7 load balancer, distributing requests via round-robin, least_conn, or ip_hash algorithms. This is the foundation for deploying microservices architectures with zero-downtime deployments.

Comparing Nginx, Apache, and IIS

Nginx vs Apache vs IIS comparison
Tested on 2026-06-12 Nginx 1.26 / Apache 2.4 / IIS 10
| Criterion | Nginx | Apache | IIS | |---|---|---|---| | Architecture | Event-driven (async) | Process/thread-per-request | Thread pool (Windows) | | High-load performance | Very high | Moderate | High (Windows) | | Configuration | Simple nginx.conf | httpd.conf + .htaccess | GUI + XML | | Dynamic modules | No (statically compiled) | Yes (.so loadable) | Yes (IIS modules) | | SSL termination | Excellent | Excellent | Excellent | | Platform support | Linux/macOS/Windows | Cross-platform | Windows only | | Cost | Free (NGINX Plus: paid) | Free | Included with Windows Server | | Best suited for | Reverse proxy, static files, K8s Ingress | PHP legacy, flexible .htaccess | Microsoft stack (.NET, [IIS](/iis-en/)) |
When should you choose Apache over Nginx?

If your application relies heavily on per-directory .htaccess files (shared hosting, WordPress plugins that write their own rewrite rules), Apache is more flexible because it reads .htaccess on every request. Nginx does not support .htaccess — all configuration must live in the central nginx.conf file.

Basic Nginx configuration

Below is a complete nginx.conf that includes a server block for serving static files, a reverse proxy to a backend, and upstream load balancing.

nginx
 1# /etc/nginx/nginx.conf
 2worker_processes auto;          # automatically match the number of CPU cores
 3events {
 4    worker_connections 1024;    # maximum connections per worker
 5}
 6
 7http {
 8    # --- Upstream: backend pool for load balancing ---
 9    upstream app_backend {
10        least_conn;             # algorithm: prefer the server with the fewest connections
11        server 10.0.0.10:8080 weight=3;
12        server 10.0.0.11:8080 weight=2;
13        server 10.0.0.12:8080 weight=1 max_fails=3 fail_timeout=30s;
14    }
15
16    # --- Server block: HTTPS + reverse proxy ---
17    server {
18        listen 443 ssl http2;
19        server_name example.com www.example.com;
20
21        ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
22        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
23        ssl_protocols       TLSv1.2 TLSv1.3;
24        ssl_ciphers         HIGH:!aNULL:!MD5;
25
26        # Serve static files directly (images, CSS, JS)
27        location /static/ {
28            root /var/www/myapp;
29            expires 30d;
30            add_header Cache-Control "public, immutable";
31        }
32
33        # Proxy all other requests to the backend pool
34        location / {
35            proxy_pass         http://app_backend;
36            proxy_set_header   Host              $host;
37            proxy_set_header   X-Real-IP         $remote_addr;
38            proxy_set_header   X-Forwarded-For   $proxy_add_x_forwarded_for;
39            proxy_set_header   X-Forwarded-Proto $scheme;
40            proxy_connect_timeout 5s;
41            proxy_read_timeout    60s;
42        }
43    }
44
45    # --- Redirect HTTP → HTTPS ---
46    server {
47        listen 80;
48        server_name example.com www.example.com;
49        return 301 https://$host$request_uri;
50    }
51}

Key directive explanations

  • worker_processes auto — Nginx auto-detects the number of CPU cores and spawns the exact right number of workers, maximizing throughput.
  • upstream — defines the backend pool; the least_conn directive selects the server with the fewest active connections instead of default round-robin.
  • proxy_set_header X-Real-IP — passes the client's real IP address to the backend; without this, the backend only sees Nginx's IP.
  • expires 30d — enables HTTP caching for static files, significantly reducing server load.

Real-world use cases

Serving static websites / JAMstack

Nginx serves the entire build output of Next.js, Hugo, or any static site generator with just a few location blocks. Nginx's static file serving speed approaches the theoretical limit of disk and network I/O — no application-layer framework can compete.

Reverse proxy for backend applications

This is the most common use case: Nginx listens on the public ports 80/443, while the backend application runs on localhost:3000 or localhost:8080 without any public exposure. Nginx handles TLS, gzip compression, and slow client connections — the backend only needs to focus on business logic.

SSL termination

Rather than installing TLS separately on each backend service, you centralize all certificate management at Nginx. The backend communicates with Nginx over plain HTTP within a private LAN — simplifying configuration and certificate renewal with Certbot.

Rate limiting — protecting your API from abuse

nginx
 1http {
 2    limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
 3
 4    server {
 5        location /api/ {
 6            limit_req zone=api_limit burst=20 nodelay;
 7            proxy_pass http://app_backend;
 8        }
 9    }
10}

The limit_req_zone directive creates a shared memory zone keyed by IP, limiting clients to 10 requests per second with a maximum burst of 20. Requests that exceed the threshold receive an HTTP 429 response directly from Nginx, consuming no backend resources.

Nginx as an Ingress Controller in Kubernetes

Inside a Kubernetes cluster, the Nginx Ingress Controller is the most popular way to expose HTTP/HTTPS services outside the cluster. An Ingress resource defined in YAML maps domains and paths to internal Services:

YAML
 1apiVersion: networking.k8s.io/v1
 2kind: Ingress
 3metadata:
 4  name: myapp-ingress
 5  annotations:
 6    nginx.ingress.kubernetes.io/rewrite-target: /
 7    nginx.ingress.kubernetes.io/limit-rps: "100"
 8spec:
 9  ingressClassName: nginx
10  tls:
11    - hosts:
12        - api.example.com
13      secretName: tls-secret
14  rules:
15    - host: api.example.com
16      http:
17        paths:
18          - path: /v1
19            pathType: Prefix
20            backend:
21              service:
22                name: api-v1-svc
23                port:
24                  number: 80
25          - path: /v2
26            pathType: Prefix
27            backend:
28              service:
29                name: api-v2-svc
30                port:
31                  number: 80

The Nginx Ingress Controller reads the Ingress resource and automatically reloads the internal nginx.conf without restarting the pod. This is how microservices systems perform rolling updates: gradually shift traffic from /v1 to /v2 simply by adjusting path rules.

Always test your configuration before reloading

Always run nginx -t before nginx -s reload. This command checks the syntax of the entire nginx.conf and all included files, returning specific errors if any are found. A reload with an invalid config is rejected automatically — Nginx will never apply a broken configuration and cause downtime.

Nginx performance tuning

Beyond the basic configuration, a few directives are often overlooked but have a significant impact on throughput:

nginx
1http {
2    sendfile        on;       # use the sendfile() syscall — zero-copy from disk to socket
3    tcp_nopush      on;       # batch multiple TCP segments before sending
4    tcp_nodelay     on;       # disable Nagle algorithm for keep-alive connections
5    keepalive_timeout 65;     # keep TCP connections open for 65 seconds (reduces repeated TLS handshakes)
6    gzip            on;
7    gzip_types      text/plain text/css application/json application/javascript;
8    gzip_min_length 1000;     # skip compression for files < 1KB (overhead outweighs benefit)
9}

sendfile on is the single most important optimization when serving large static files — the kernel transfers data directly from the page cache to the socket without copying through user space.

Conclusion: Nginx is far more than a web server — it is a comprehensive traffic orchestration layer for modern architectures. Whether you are serving a static SPA, proxying a Node.js backend, load-balancing microservices, or need an Ingress Controller for Kubernetes, Nginx delivers a consistent, high-performance, and transparently configurable solution in a single binary.

Sources

What is API Gateway? The entry point for microservices

Frequently Asked Questions

Frequently Asked QuestionsQ&A
What is the most important difference between Nginx and Apache?
Apache handles each request with its own thread or process (prefork/worker MPM), which consumes significant RAM under many concurrent connections. Nginx uses an asynchronous, event-driven architecture — a single worker process can handle thousands of connections simultaneously with very low memory usage. For high-traffic workloads with many idle (keep-alive) connections, Nginx holds a clear performance advantage.
What is a reverse proxy, and why use Nginx as one?
A reverse proxy is an intermediary server that sits in front of your internal servers, receiving requests from clients and forwarding them to the appropriate backend. Using Nginx as a reverse proxy lets you hide backend addresses, centralize SSL termination, enable caching and gzip compression, and protect your application from direct attacks.
How does Nginx perform load balancing?
Nginx supports multiple load-balancing algorithms via the upstream directive: round-robin (default), least_conn (fewest active connections), ip_hash (same IP always reaches the same server), and random. Each server in an upstream block can be assigned a weight and max_fails value to control traffic distribution and automatically remove unhealthy servers from the pool.
Can Nginx replace an application server?
It should not. Nginx cannot run Python, PHP, or Node.js code directly. The correct role for Nginx is to receive requests from the internet, serve static files immediately, and proxy_pass everything else to Gunicorn, PHP-FPM, a Node.js process, or any other application server that is listening. This combination optimizes both performance and security.
How do you configure SSL/TLS on Nginx?
In the server block listening on port 443, add ssl_certificate pointing to your .pem file and ssl_certificate_key pointing to your private key. Enable TLS 1.2/1.3 via ssl_protocols and select strong cipher suites via ssl_ciphers. Use a listen 80 block combined with return 301 to automatically redirect HTTP to HTTPS. With Let's Encrypt, the Certbot tool writes these directives automatically.