Nginx
# 1. Nginx 简介
# 1.1 Nginx 是什么?
Nginx(发音:Engine-X)是一款高性能、轻量级的开源 Web 服务器和反向代理服务器,同时也可以作为负载均衡器和 HTTP 缓存服务器。它由俄罗斯工程师 Igor Sysoev 于 2004 年首次发布,旨在解决 C10K(同时处理 10,000 个并发连接)问题。
目前,Nginx 已广泛应用于各种互联网服务,如网站托管、API 网关、反向代理、微服务架构等。许多知名网站(如 Netflix、GitHub、WordPress.com 等)都在使用 Nginx 作为其核心 Web 服务器。
# 1.2 Nginx 的主要特点与优势
Nginx 之所以流行,主要得益于以下几个特点和优势:
- 高并发处理能力
- Nginx 采用**事件驱动(Event-Driven)+ 异步非阻塞(Asynchronous Non-blocking)**架构,能高效处理大规模并发请求,远优于传统的基于线程或进程的服务器。
- 由于其高效的多路复用(Multiplexing)能力,即使面对高并发流量,Nginx 也能保持低资源消耗。
- 轻量级,资源占用低
- Nginx 使用较少的内存和 CPU 资源,通常比 Apache 服务器更节省资源。
- 典型情况下,每个 Nginx 进程占用的内存极小,适合运行在高并发、高负载的环境中。
- 反向代理与负载均衡
- Nginx 可以作为反向代理服务器,将请求转发到后端服务器,同时支持多种负载均衡策略(如轮询、最少连接、IP 哈希等)。
- 还可以与 Keepalived 结合,实现高可用(HA)。
- 支持静态资源高效处理
- Nginx 非常适合处理静态资源(如 HTML、CSS、JavaScript、图片、视频等),可直接从磁盘读取并高效返回给客户端。
- 结合缓存机制(如 FastCGI Cache、Proxy Cache),可以进一步提升访问速度。
- 模块化设计,功能强大
- Nginx 通过模块扩展支持 HTTPS、WebSocket、Gzip 压缩、访问控制等功能。
- 还可以通过第三方模块扩展更多特性,如 Lua 脚本、JWT 认证、DDoS 保护等。
- 支持 HTTP/2 与 HTTPS
- Nginx 内置支持 HTTP/2,可提高多路复用效率,降低页面加载时间。
- 通过 Let's Encrypt 轻松配置 SSL 证书,实现 HTTPS 安全通信。
- 跨平台支持
- Nginx 主要运行在 Linux 系统上,同时支持 Windows、macOS 等操作系统。
- 热部署,无需重启
- Nginx 的配置修改可以在不中断服务的情况下生效(热重载),避免传统服务器重启导致的宕机问题。
# 1.3 Nginx vs Apache
特性对比 | Nginx | Apache |
---|---|---|
架构 | 事件驱动、异步非阻塞 | 进程/线程驱动、阻塞式 |
并发性能 | 适合高并发,轻量级 | 高并发场景下占用资源较多 |
静态资源处理 | 高效,直接从内存或磁盘读取 | 处理速度较慢 |
动态内容处理 | 需要配合 FastCGI(如 PHP-FPM) | 可直接通过 mod_php 处理 |
负载均衡 | 内置支持 | 需要额外配置 |
配置管理 | 配置文件简洁清晰 | 配置文件较为复杂 |
扩展性 | 模块化设计,可动态加载模块 | 需编译时选择模块 |
跨平台支持 | 主要适用于 Linux,Windows 版功能较弱 | Linux、Windows、macOS 均支持 |
应用场景 | 反向代理、负载均衡、微服务架构、CDN | 传统网站托管、动态内容管理 |
总结:
- 如果你的应用主要是静态资源服务、高并发场景、反向代理和负载均衡,那么 Nginx 是更好的选择。
- 如果你的应用主要是动态内容(如 PHP),并且不需要高并发处理,那么 Apache 可能更简单易用。
- 很多时候,Nginx 与 Apache 也可以配合使用,如:Nginx 作为前端代理服务器,Apache 处理后端动态请求。
这部分内容详细介绍了 Nginx 的核心概念,你觉得还需要补充哪些内容?
# 2. Nginx 安装与基本配置
# 2.1 在 Linux(Ubuntu/CentOS)上安装 Nginx
# 2.1.1 在 Ubuntu/Debian 安装 Nginx
Ubuntu 和 Debian 可以使用 APT 包管理工具安装 Nginx:
# 更新软件源
sudo apt update
# 安装 Nginx
sudo apt install nginx -y
# 启动 Nginx
sudo systemctl start nginx
# 设置开机自启
sudo systemctl enable nginx
# 查看 Nginx 运行状态
sudo systemctl status nginx
2
3
4
5
6
7
8
9
10
11
12
13
14
安装完成后,可以在浏览器访问 http://服务器IP
,如果看到 Welcome to Nginx 页面,说明安装成功。
# 2.1.2 在 CentOS/RHEL 安装 Nginx
CentOS/RHEL 使用 yum
或 dnf
进行安装:
# 安装 EPEL 源(如果需要)
sudo yum install epel-release -y
# 安装 Nginx
sudo yum install nginx -y
# 启动 Nginx
sudo systemctl start nginx
# 设置开机自启
sudo systemctl enable nginx
# 查看 Nginx 运行状态
sudo systemctl status nginx
2
3
4
5
6
7
8
9
10
11
12
13
14
# 2.1.3 开放防火墙端口
如果服务器开启了防火墙,需要允许 HTTP 和 HTTPS 端口(80 和 443):
# 允许 HTTP 端口(80)
sudo firewall-cmd --permanent --add-service=http
# 允许 HTTPS 端口(443)
sudo firewall-cmd --permanent --add-service=https
# 重新加载防火墙规则
sudo firewall-cmd --reload
2
3
4
5
6
7
8
# 2.2 在 Windows/Mac 上安装 Nginx
# 2.2.1 在 Windows 安装 Nginx
下载 Nginx
- 访问 Nginx 官方网站 (opens new window) 下载 Windows 版本的 Nginx。
- 下载
.zip
文件后,解压到C:\nginx
(或其他路径)。
启动 Nginx
在解压目录下,运行 cmd(命令提示符),输入:
cd C:\nginx start nginx
1
2访问
http://localhost
,如果出现 Welcome to Nginx 页面,则表示成功。
停止或重启 Nginx
nginx -s stop # 停止 Nginx nginx -s reload # 重新加载配置
1
2
# 2.2.2 在 macOS 安装 Nginx
使用 Homebrew 安装(推荐)
brew install nginx
1启动 Nginx
sudo nginx
1停止或重启 Nginx
sudo nginx -s stop # 停止 Nginx sudo nginx -s reload # 重新加载配置
1
2验证安装
在浏览器访问http://localhost
,如果看到 Welcome to Nginx 页面,表示安装成功。
# 2.3 Nginx 目录结构和配置文件解析
Nginx 主要的目录和配置文件如下(以 Linux 版本为例):
/etc/nginx/
├── nginx.conf # 主配置文件
├── conf.d/ # 额外的配置文件目录
│ ├── default.conf # 默认站点配置
│ ├── ssl.conf # SSL 配置
├── sites-available/ # 可用站点配置(部分系统使用)
│ ├── example.com.conf
├── sites-enabled/ # 启用站点的配置(部分系统使用)
│ ├── example.com.conf -> ../sites-available/example.com.conf
├── html/ # 默认网页存放目录
│ ├── index.html # 默认首页
├── logs/ # 日志文件目录
│ ├── access.log # 访问日志
│ ├── error.log # 错误日志
└── modules/ # Nginx 模块
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 2.3.1 Nginx 主配置文件(nginx.conf)解析
主配置文件 /etc/nginx/nginx.conf
主要由以下几个部分组成:
worker_processes auto; # 进程数,通常设置为 CPU 核心数
events {
worker_connections 1024; # 每个 worker 进程最大连接数
}
http {
include mime.types; # 载入 MIME 类型
default_type application/octet-stream;
sendfile on; # 开启高效文件传输
keepalive_timeout 65; # 连接保持时间
server {
listen 80; # 监听端口
server_name localhost; # 服务器域名
location / {
root /usr/share/nginx/html; # 网站根目录
index index.html index.htm; # 默认首页
}
error_page 404 /404.html; # 404 错误页面
location = /404.html {
root /usr/share/nginx/html;
}
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 2.3.2 站点配置文件(conf.d/default.conf)
/etc/nginx/conf.d/default.conf
可能是默认的站点配置:
server {
listen 80;
server_name example.com www.example.com;
location / {
root /var/www/html;
index index.html index.htm;
}
}
2
3
4
5
6
7
8
9
server_name example.com www.example.com;
指定域名。root /var/www/html;
指定网站的根目录。index index.html index.htm;
设置默认访问的首页。
# 2.3.3 日志配置
Nginx 默认的日志文件存放在 /var/log/nginx/
:
- 访问日志:
/var/log/nginx/access.log
- 错误日志:
/var/log/nginx/error.log
如果需要更详细的日志,可以修改 nginx.conf
:
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log warn;
2
# 2.3.4 重新加载 Nginx 配置
修改配置后,需重新加载 Nginx 使其生效:
sudo nginx -s reload
# 3. Nginx 作为 Web 服务器
Nginx 作为 Web 服务器的主要用途包括:
- 提供静态资源服务(HTML、CSS、JS、图片等)
- 处理动态请求(配合 PHP-FPM、FastCGI 运行 PHP 等动态语言)
- 反向代理与负载均衡(代理后端应用服务器,如 Node.js、Python、Java 等)
# 3.1 配置静态资源服务器
Nginx 作为静态资源服务器时,可以直接提供 HTML、CSS、JS、图片、视频等文件。
# 3.1.1 基本配置
在 /etc/nginx/conf.d/default.conf
或 /etc/nginx/nginx.conf
文件中的 server
块中,添加以下内容:
server {
listen 80; # 监听 80 端口
server_name example.com; # 绑定域名(可用 IP 地址替代)
root /var/www/html; # 指定网站根目录
index index.html index.htm; # 默认首页
location / {
try_files $uri $uri/ =404; # 如果文件不存在,则返回 404
}
location /images/ {
root /var/www/static; # 另一个目录专门存放图片
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
root /var/www/html;
:指定网页存放目录index index.html index.htm;
:设置默认访问的首页try_files $uri $uri/ =404;
:如果文件不存在,则返回 404location /images/
:可以为不同类型的资源指定不同的目录
# 3.1.2 启用 Gzip 压缩(优化性能)
为了提升静态资源的传输效率,可以开启 Gzip 压缩:
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
gzip_comp_level 6;
gzip_min_length 1000;
2
3
4
# 3.2 处理动态请求(FastCGI、PHP-FPM)
Nginx 本身无法直接解析 PHP、Python、Ruby 等动态语言,需要与 FastCGI 进程管理器(如 PHP-FPM)配合使用。
# 3.2.1 运行 PHP(Nginx + PHP-FPM)
# 1. 安装 PHP-FPM
在 Ubuntu / Debian:
sudo apt install php-fpm -y
在 CentOS:
sudo yum install php-fpm -y
然后启动 PHP-FPM:
sudo systemctl start php-fpm
sudo systemctl enable php-fpm
2
# 2. 配置 Nginx 处理 PHP
编辑 /etc/nginx/conf.d/default.conf
,增加 PHP 解析支持:
server {
listen 80;
server_name example.com;
root /var/www/html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include fastcgi_params; # FastCGI 相关参数
fastcgi_pass unix:/run/php/php7.4-fpm.sock; # PHP-FPM 监听的 Unix socket
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
注意:
fastcgi_pass unix:/run/php/php7.4-fpm.sock;
在不同系统版本可能不同,使用find /run/php/ -name "*.sock"
确认路径- 也可以使用
fastcgi_pass 127.0.0.1:9000;
,表示 PHP-FPM 监听 TCP 端口
# 3. 测试 PHP
在 /var/www/html/
目录下创建 info.php
文件:
<?php
phpinfo();
?>
2
3
然后访问 http://example.com/info.php
,如果能看到 PHP 信息页面,则说明 Nginx 已成功解析 PHP。
# 4. Nginx 反向代理与负载均衡
Nginx 作为反向代理(Reverse Proxy)时,可以将客户端请求转发到后端服务器,并在此过程中隐藏真实的后端服务器信息,起到安全、性能优化和负载均衡的作用。
本章介绍:
- 配置反向代理
- 负载均衡策略
- 健康检查与故障转移
# 4.1 配置反向代理(proxy_pass)
# 4.1.1 反向代理基本配置
假设后端应用服务器运行在 127.0.0.1:3000,Nginx 需要作为反向代理,将外部请求转发到该服务。
Nginx 配置示例(/etc/nginx/conf.d/default.conf
或 /etc/nginx/nginx.conf
):
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://127.0.0.1:3000; # 代理到后端应用
proxy_set_header Host $host; # 传递原始 Host 头
proxy_set_header X-Real-IP $remote_addr; # 传递真实 IP
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # 记录转发链
}
}
2
3
4
5
6
7
8
9
10
11
关键配置说明:
proxy_pass http://127.0.0.1:3000;
:将请求转发到后端服务器proxy_set_header Host $host;
:确保后端服务器可以获取客户端请求的原始域名proxy_set_header X-Real-IP $remote_addr;
:传递客户端真实 IPproxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
:支持多级代理时的客户端 IP 追踪
访问
http://example.com
,请求将被转发到http://127.0.0.1:3000
。
# 4.2 负载均衡策略
当有多个后端服务器时,Nginx 可以通过负载均衡策略自动分配请求,以提高系统吞吐能力和可靠性。
# 4.2.1 配置多个后端服务器
upstream backend_servers {
server 192.168.1.10:3000;
server 192.168.1.11:3000;
server 192.168.1.12:3000;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend_servers;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
说明:
upstream backend_servers {}
:定义一组后端服务器proxy_pass http://backend_servers;
:将请求分配到backend_servers
组中的服务器
# 4.2.2 负载均衡策略
Nginx 支持多种负载均衡策略:
# 1. 轮询(默认,Round Robin)
upstream backend_servers {
server 192.168.1.10:3000;
server 192.168.1.11:3000;
}
2
3
4
- Nginx 默认采用轮询,依次将请求分配给不同的后端服务器。
# 2. 最少连接数(least_conn)
upstream backend_servers {
least_conn;
server 192.168.1.10:3000;
server 192.168.1.11:3000;
}
2
3
4
5
- 适用于长连接应用(如 WebSocket),Nginx 会优先分配请求给当前连接数最少的服务器。
# 3. IP 哈希(ip_hash)
upstream backend_servers {
ip_hash;
server 192.168.1.10:3000;
server 192.168.1.11:3000;
}
2
3
4
5
- 保证相同 IP 地址的请求始终转发到同一台服务器,适用于需要会话保持(session stickiness)的场景,如认证系统。
# 4. 权重(weight)
upstream backend_servers {
server 192.168.1.10:3000 weight=3; # 处理更多请求
server 192.168.1.11:3000 weight=1;
}
2
3
4
- 权重越大,分配的请求越多,适用于服务器性能不均的情况。
# 5. 备用服务器(backup)
upstream backend_servers {
server 192.168.1.10:3000;
server 192.168.1.11:3000 backup;
}
2
3
4
backup
服务器仅在主服务器全部故障时才启用,提高系统容错能力。
# 4.3 健康检查与故障转移
Nginx 本身不具备主动健康检查功能,但可以使用 max_fails
和 fail_timeout
进行基础故障检测。
# 4.3.1 服务器故障检测
upstream backend_servers {
server 192.168.1.10:3000 max_fails=3 fail_timeout=30s;
server 192.168.1.11:3000;
}
2
3
4
max_fails=3
:连续 3 次请求失败后,标记该服务器为不可用fail_timeout=30s
:服务器 30 秒后重新尝试
如果 192.168.1.10
服务器在 30 秒内连续 3 次返回错误(如 502、504),Nginx 会暂时将其移除,直到恢复为止。
# 4.3.2 使用 Nginx ngx_http_healthcheck_module
Nginx 商业版支持主动健康检查,可定期探测后端服务器状态。
对于开源版本,可以使用 nginx_upstream_check_module
插件或结合 keepalived
进行健康检查。
# 4.3.3 结合 Keepalived 实现高可用
当Nginx 服务器本身故障时,可以结合 keepalived
,在主备服务器之间进行 IP 漂移,实现高可用:
sudo apt install keepalived
示例 Keepalived 配置:
vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 51
priority 100
advert_int 1
virtual_ipaddress {
192.168.1.100
}
}
2
3
4
5
6
7
8
9
10
作用:
- 如果主 Nginx 服务器宕机,VIP(虚拟 IP)会自动切换到备用服务器。
- 确保 Nginx 整体服务高可用。
# 5. Nginx 安全与优化
Nginx 作为高性能 Web 服务器和反向代理,除了提供强大的功能外,还需要在安全和优化方面进行配置,以增强系统的稳定性、抗攻击能力以及提升性能。
本章主要介绍:
- 启用 HTTPS(Let’s Encrypt、SSL 证书)
- 限流与防止 DDoS 攻击
- 日志分析与监控
# 5.1 启用 HTTPS(Let’s Encrypt、SSL 证书)
HTTPS 通过 SSL/TLS 加密数据传输,防止中间人攻击,提高网站安全性。
# 5.1.1 使用 Let’s Encrypt 申请免费 SSL 证书
Let’s Encrypt 提供免费的 SSL 证书,可以使用 certbot
申请和自动续期。
# 1. 安装 Certbot
Ubuntu/Debian:
sudo apt update
sudo apt install certbot python3-certbot-nginx -y
2
CentOS:
sudo yum install epel-release -y
sudo yum install certbot python3-certbot-nginx -y
2
# 2. 申请 SSL 证书
sudo certbot --nginx -d example.com -d www.example.com
Certbot 会自动配置 Nginx 并申请 SSL 证书。
# 3. 自动续期
sudo certbot renew --dry-run
Certbot 会自动续期证书,无需手动操作。
# 5.1.2 手动配置 SSL 证书
如果你有自己的 SSL 证书(.crt
和 .key
文件),可以手动配置 Nginx:
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/nginx/ssl/example.com.crt;
ssl_certificate_key /etc/nginx/ssl/example.com.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
location / {
root /var/www/html;
index index.html;
}
}
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
return 301 https://$host$request_uri;
强制 HTTP 重定向到 HTTPS。
# 5.2 限流与防止 DDoS 攻击
# 5.2.1 限制每个 IP 的请求速率
使用 limit_req_zone
限制单个 IP 的请求速率:
http {
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
server {
listen 80;
server_name example.com;
location / {
limit_req zone=one burst=20 nodelay;
}
}
}
2
3
4
5
6
7
8
9
10
11
12
说明:
rate=10r/s
:每个 IP 每秒最多请求 10 次burst=20
:允许短时间内突发 20 个请求nodelay
:超出速率的请求立即返回 503(否则会排队)
# 5.2.2 限制连接数
使用 limit_conn
限制 IP 的并发连接数:
http {
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
listen 80;
server_name example.com;
location / {
limit_conn addr 5; # 每个 IP 最多 5 个并发连接
}
}
}
2
3
4
5
6
7
8
9
10
11
12
# 5.2.3 防止恶意请求
Nginx 可以屏蔽一些恶意的 User-Agent 和 Referer:
server {
location / {
if ($http_user_agent ~* (malicious_bot|bad_crawler) ) {
return 403;
}
if ($http_referer ~* (spam-site.com|bad-link.com) ) {
return 403;
}
}
}
2
3
4
5
6
7
8
9
10
# 5.2.4 通过 fail2ban 阻止恶意 IP
Fail2Ban 可以自动检测恶意请求,并临时封禁 IP:
sudo apt install fail2ban -y
配置 /etc/fail2ban/jail.local
:
[nginx-http-auth]
enabled = true
filter = nginx-http-auth
action = iptables-multiport[name=NoAuthFailures, port="http,https", protocol=tcp]
logpath = /var/log/nginx/access.log
maxretry = 5
findtime = 600
bantime = 3600
2
3
4
5
6
7
8
效果:如果某个 IP 在 10 分钟内失败 5 次,则封禁 1 小时。
# 5.3 日志分析与监控
# 5.3.1 启用访问日志
Nginx 默认会记录访问日志,可在 nginx.conf
配置:
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
2
3
4
5
访问日志包含IP、时间、请求地址、状态码、User-Agent等信息。
# 5.3.2 启用错误日志
error_log /var/log/nginx/error.log warn;
error_log
级别可选debug | info | notice | warn | error | crit
。
# 5.3.3 使用 GoAccess 进行日志分析
安装 GoAccess:
sudo apt install goaccess -y
使用 GoAccess 分析 Nginx 日志:
goaccess /var/log/nginx/access.log --log-format=COMBINED -o report.html
生成的
report.html
可在浏览器中查看访问统计信息。
# 5.3.4 使用 Prometheus + Grafana 监控 Nginx
安装 Nginx VTS 模块
sudo apt install nginx-module-vts
1配置 Nginx 统计接口
location /status { vhost_traffic_status_display; vhost_traffic_status_display_format html; }
1
2
3
4使用 Prometheus + Grafana 采集并可视化流量数据
# 6. Nginx 高级功能
Nginx 除了作为高性能 Web 服务器和反向代理,还提供了丰富的高级功能,如 URL 重写、WebSocket 代理以及性能优化(如 Gzip 压缩和缓存)。
本章主要介绍:
- Rewrite 规则与 URL 重写
- 配置 WebSocket 代理
- Gzip 压缩与缓存优化
# 6.1 Rewrite 规则与 URL 重写
Nginx 提供 rewrite
指令用于修改 URL,常用于URL 重定向、伪静态 和 SEO 优化。
# 6.1.1 Rewrite 语法
rewrite 正则表达式 替换字符串 [flag];
常见标志(flag)说明:
last
:匹配成功后停止,继续匹配后续 location 规则break
:匹配成功后立即返回,不再继续匹配redirect
:临时重定向(302)permanent
:永久重定向(301)
# 6.1.2 典型 Rewrite 规则
# 1. URL 规范化(www 跳转)
强制 www.example.com
跳转到 example.com
:
server {
listen 80;
server_name www.example.com;
rewrite ^(.*)$ http://example.com$1 permanent;
}
2
3
4
5
permanent
代表 301 永久重定向,适用于 SEO 优化。
# 2. 伪静态(隐藏 .php)
将 example.com/news/123
映射到 example.com/news.php?id=123
:
location /news/ {
rewrite ^/news/([0-9]+)$ /news.php?id=$1 last;
}
2
3
# 3. 强制 HTTPS 重定向
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
2
3
4
5
# 4. 防止恶意解析(禁止访问 .php.txt)
location ~ \.(php|php5|php7)\.txt$ {
return 403;
}
2
3
# 6.2 配置 WebSocket 代理
Nginx 可代理 WebSocket 连接,使其在 Web 服务器后端运行,如代理 ws://
或 wss://
请求。
# 6.2.1 代理 WebSocket
假设 WebSocket 服务器运行在 127.0.0.1:8080
:
server {
listen 80;
server_name example.com;
location /ws/ {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header Host $host;
}
}
2
3
4
5
6
7
8
9
10
11
12
关键配置说明:
proxy_http_version 1.1;
:确保使用 HTTP/1.1proxy_set_header Upgrade $http_upgrade;
:支持 WebSocket 连接升级proxy_set_header Connection "Upgrade";
:确保代理正确处理连接
# 6.2.2 WebSocket + SSL(wss://)
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/nginx/ssl/example.com.crt;
ssl_certificate_key /etc/nginx/ssl/example.com.key;
location /ws/ {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
适用于 WebSocket 需要加密通信(
wss://
)的情况。
# 6.3 Gzip 压缩与缓存优化
Nginx 通过 Gzip 压缩和缓存策略,减少带宽占用,加速网页加载。
# 6.3.1 启用 Gzip 压缩
Gzip 可以压缩 HTML、CSS、JavaScript 等静态资源,提高加载速度。
# 1. 配置 Gzip
http {
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
gzip_vary on;
gzip_min_length 1000;
gzip_comp_level 5;
}
2
3
4
5
6
7
参数说明:
gzip on;
:开启 Gzip 压缩gzip_types
:指定压缩的 MIME 类型gzip_vary on;
:支持代理服务器缓存不同 Gzip 版本gzip_min_length 1000;
:小于 1KB 的数据不压缩gzip_comp_level 5;
:压缩等级(1-9),5 是推荐值
# 2. 验证 Gzip 是否生效
curl -H "Accept-Encoding: gzip" -I http://example.com
如果
Content-Encoding: gzip
存在,则说明压缩成功。
# 6.3.2 配置浏览器缓存
浏览器缓存减少重复请求,加速页面加载。
# 1. 静态资源缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2|ttf|svg|mp4|webp)$ {
expires 30d;
add_header Cache-Control "public, max-age=2592000";
}
2
3
4
说明:
expires 30d;
:缓存 30 天Cache-Control: max-age=2592000;
:客户端缓存 30 天
# 2. 强制资源更新
如果更新了 style.css
,但浏览器仍然使用旧版本,可以:
- 修改 URL,如
style.css?v=2
- 结合
etag
或last-modified
location /static/ {
etag on;
expires 7d;
add_header Cache-Control "public, max-age=604800, must-revalidate";
}
2
3
4
5
# 6.3.3 启用 FastCGI 缓存
适用于 PHP 站点,减少 PHP 服务器负载。
fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=PHP_CACHE:10m inactive=60m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
server {
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_cache PHP_CACHE;
fastcgi_cache_valid 200 302 10m;
fastcgi_cache_valid 404 1m;
fastcgi_cache_use_stale error timeout updating;
}
}
2
3
4
5
6
7
8
9
10
11
12
适用于 WordPress、Discuz 等动态网站。
# 7. Nginx 与容器化部署
Nginx 作为轻量级、高性能的 Web 服务器,非常适合容器化部署。
本章将介绍:
- 在 Docker 中运行 Nginx
- Nginx 结合 Kubernetes(Ingress 配置)
# 7.1 在 Docker 中运行 Nginx
使用 Docker 部署 Nginx,可以快速创建、管理和扩展 Web 服务器,同时避免繁琐的环境配置。
# 7.1.1 拉取 Nginx 官方镜像
docker pull nginx
这个命令会拉取最新的 Nginx 官方镜像(默认
latest
版本)。
# 7.1.2 运行 Nginx 容器
docker run -d --name my-nginx -p 8080:80 nginx
参数说明:
-d
:后台运行容器--name my-nginx
:容器名称-p 8080:80
:映射主机端口8080
到容器的80
端口nginx
:使用nginx
官方镜像
访问 http://localhost:8080
,可以看到默认的 Nginx 欢迎页面。
# 7.1.3 挂载自定义配置
Docker 容器中的 Nginx 配置文件路径是 /etc/nginx/nginx.conf
,可以挂载本地配置文件:
docker run -d --name my-nginx -p 8080:80 \
-v /path/to/nginx.conf:/etc/nginx/nginx.conf \
-v /path/to/html:/usr/share/nginx/html \
nginx
2
3
4
说明:
-v /path/to/nginx.conf:/etc/nginx/nginx.conf
:挂载 Nginx 配置文件-v /path/to/html:/usr/share/nginx/html
:挂载静态资源目录
# 7.1.4 使用 Docker Compose
Docker Compose 方便管理多个容器,例如同时运行 Nginx 和 PHP(PHP-FPM):
version: '3'
services:
nginx:
image: nginx
container_name: nginx
ports:
- "8080:80"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
- ./html:/usr/share/nginx/html
depends_on:
- php
php:
image: php:fpm
container_name: php
volumes:
- ./html:/usr/share/nginx/html
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
运行:
docker-compose up -d
这样 Nginx 可以与 PHP-FPM 协同工作,提供动态请求处理。
# 7.2 Nginx 结合 Kubernetes(Ingress 配置)
在 Kubernetes(K8s)集群中,Nginx 可以作为 Ingress Controller 处理外部流量。
# 7.2.1 安装 Nginx Ingress Controller
在 Kubernetes 中,Ingress
负责将外部请求路由到内部服务。Nginx Ingress Controller 是最常见的 Ingress 实现。
可以使用 Helm
安装:
helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx
helm repo update
helm install my-ingress ingress-nginx/ingress-nginx
2
3
安装完成后,会在集群中创建
ingress-nginx
控制器。
# 7.2.2 部署 Nginx 作为 Pod
创建 nginx-deployment.yaml
:
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
spec:
replicas: 2
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:latest
ports:
- containerPort: 80
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
应用:
kubectl apply -f nginx-deployment.yaml
# 7.2.3 创建 Nginx Service
apiVersion: v1
kind: Service
metadata:
name: nginx-service
spec:
selector:
app: nginx
ports:
- protocol: TCP
port: 80
targetPort: 80
type: ClusterIP
2
3
4
5
6
7
8
9
10
11
12
应用:
kubectl apply -f nginx-service.yaml
# 7.2.4 配置 Ingress 规则
创建 nginx-ingress.yaml
:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: nginx-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
ingressClassName: nginx
rules:
- host: my-nginx.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: nginx-service
port:
number: 80
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
应用:
kubectl apply -f nginx-ingress.yaml
说明:
host: my-nginx.example.com
:绑定域名service.name: nginx-service
:流量转发到 Nginx Servicenginx.ingress.kubernetes.io/rewrite-target: /
:重写 URL
# 7.2.5 访问 Ingress
如果使用 minikube
,可以获取 Ingress 的外部 IP:
minikube service nginx-service --url
如果是云环境,可以使用 kubectl get ingress
查看 EXTERNAL-IP
:
kubectl get ingress
然后访问 http://my-nginx.example.com
即可。