前言

Nginx(发音 “Engine-X”)是一款高性能的 HTTP 和反向代理服务器。它以占用内存少、并发能力强、配置灵活著称,国内几乎所有互联网公司都在使用。

本文从核心场景出发,带你掌握 Nginx 最实用的功能。

Nginx 能做什么?

场景 说明
🏠 静态网站托管 托管 HTML/CSS/JS 文件
🔄 反向代理 隐藏后端服务,统一入口
⚖️ 负载均衡 将请求分发到多台服务器
🔒 HTTPS 配置 SSL/TLS 证书配置
📦 静态资源缓存 CSS/JS/图片缓存优化
🛡️ 安全防护 限流、防盗链、IP 黑白名单

一、安装与基础命令

1
2
3
4
5
6
7
8
# Ubuntu/Debian
sudo apt install nginx

# CentOS/RHEL
sudo yum install nginx

# macOS
brew install nginx

常用命令:

1
2
3
4
5
6
7
8
nginx -v                          # 查看版本
nginx -t # 测试配置文件语法
sudo nginx -s reload # 平滑重启(不中断服务)
sudo nginx -s stop # 快速停止
sudo nginx -s quit # 优雅停止
sudo systemctl start nginx # systemd 启动
sudo systemctl enable nginx # 开机自启
sudo systemctl status nginx # 查看状态

二、配置文件结构

1
2
3
4
5
6
# 主配置文件
/etc/nginx/nginx.conf

# 站点配置(分文件管理,推荐)
/etc/nginx/sites-available/ # 可用站点
/etc/nginx/sites-enabled/ # 已启用站点(软链接)

最小 nginx.conf:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
worker_processes  auto;                  # 自动检测 CPU 核心数

events {
worker_connections 1024; # 每个 worker 的最大连接数
}

http {
include mime.types;
default_type application/octet-stream;

# 日志格式
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" ';

access_log /var/log/nginx/access.log main;

sendfile on;
keepalive_timeout 65;

# 引入站点配置
include /etc/nginx/sites-enabled/*;
}

三、静态网站托管

1
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
server {
listen 80;
server_name blog.iot2045.cn;
root /var/www/blog;
index index.html index.htm;

# 日志
access_log /var/log/nginx/blog_access.log;
error_log /var/log/nginx/blog_error.log;

# 静态资源缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}

# SPA 应用(如 Vue/React):所有路由指向 index.html
location / {
try_files $uri $uri/ /index.html;
}

# 禁止访问隐藏文件
location ~ /\. {
deny all;
}
}

启用站点:

1
2
sudo ln -s /etc/nginx/sites-available/blog /etc/nginx/sites-enabled/
sudo nginx -t && sudo nginx -s reload

四、反向代理(最核心功能)⭐

反向代理让 Nginx 作为前端网关,将请求转发给后端应用。

1
用户 → Nginx (80/443) → 后端应用 (3000)
1
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
30
31
32
33
34
server {
listen 80;
server_name api.example.com;

location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;

# 传递客户端真实 IP 和协议
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;

# WebSocket 支持
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";

# 超时设置
proxy_connect_timeout 60s;
proxy_read_timeout 60s;
proxy_send_timeout 60s;

# 缓冲设置
proxy_buffering on;
proxy_buffer_size 4k;
}

# 只代理 /api 路径
location /api {
proxy_pass http://127.0.0.1:8080;
include proxy_params; # 公共参数可提取到单独文件
}
}

多服务代理示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
server {
listen 80;
server_name mysite.com;

# 前端
location / {
proxy_pass http://127.0.0.1:3000;
}

# 后端 API
location /api {
proxy_pass http://127.0.0.1:8080;
}

# 文件服务
location /files {
proxy_pass http://127.0.0.1:9000;
}
}

五、负载均衡

将请求分发到多个后端服务器,提高可用性和吞吐量。

5.1 基础配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 定义上游服务器组
upstream backend {
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
}

server {
listen 80;
server_name api.example.com;

location / {
proxy_pass http://backend;
}
}

5.2 负载均衡策略

1
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
30
31
32
33
# 1. 轮询(默认):逐个分配
upstream backend {
server 192.168.1.10:8080;
server 192.168.1.11:8080;
}

# 2. 加权轮询:高性能机器多分配
upstream backend {
server 192.168.1.10:8080 weight=3; # 3/5 的请求
server 192.168.1.11:8080 weight=2; # 2/5 的请求
}

# 3. IP Hash:同一 IP 始终访问同一服务器(解决 Session 问题)
upstream backend {
ip_hash;
server 192.168.1.10:8080;
server 192.168.1.11:8080;
}

# 4. 最少连接:分配请求到连接数最少的服务器
upstream backend {
least_conn;
server 192.168.1.10:8080;
server 192.168.1.11:8080;
}

# 5. 带健康检查
upstream backend {
server 192.168.1.10:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.11:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.12:8080 backup; # 备用服务器,主服务器都挂了才用
server 192.168.1.13:8080 down; # 手动下线
}

六、HTTPS 配置

1
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
server {
listen 443 ssl http2;
server_name blog.iot2045.cn;

# 证书配置
ssl_certificate /etc/nginx/ssl/fullchain.pem;
ssl_certificate_key /etc/nginx/ssl/privkey.pem;

# 安全协议(禁用旧版本)
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;

# 启用 OCSP Stapling(加速证书验证)
ssl_stapling on;
ssl_stapling_verify on;

root /var/www/blog;
index index.html;
}

# HTTP 自动跳转 HTTPS
server {
listen 80;
server_name blog.iot2045.cn;
return 301 https://$server_name$request_uri;
}

💡 免费 SSL 证书推荐使用 Let’s Encrypt + Certbot 自动签发和续期。


七、性能优化

1
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
30
31
32
33
34
# 1. Gzip 压缩(减少传输体积)
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_comp_level 6; # 压缩级别(1-9)
gzip_types text/plain text/css application/json
application/javascript text/xml application/xml
text/javascript image/svg+xml;

# 2. 静态资源缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff2)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}

# 3. 限制请求速率(防 CC 攻击)
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;

location /login {
limit_req zone=one burst=20 nodelay;
proxy_pass http://backend;
}

# 4. 限制连接数
limit_conn_zone $binary_remote_addr zone=addr:10m;

server {
limit_conn addr 10; # 每个 IP 最多 10 个并发连接
}

# 5. 开启 sendfile
sendfile on;
tcp_nopush on;
tcp_nodelay on;

八、实用配置片段

1
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
30
31
32
33
34
35
36
# 1. 防盗链
location ~* \.(jpg|png|gif)$ {
valid_referers none blocked blog.iot2045.cn *.iot2045.cn;
if ($invalid_referer) {
return 403;
}
}

# 2. IP 白名单
location /admin {
allow 192.168.1.0/24;
allow 10.0.0.100;
deny all;
}

# 3. 自定义错误页面
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;

# 4. 跨域配置
location /api {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, OPTIONS';
add_header Access-Control-Allow-Headers 'Content-Type, Authorization';

if ($request_method = 'OPTIONS') {
return 204; # 预检请求直接返回
}

proxy_pass http://backend;
}

# 5. URL 重写
location /old-page {
rewrite ^/old-page(.*)$ /new-page$1 permanent; # 301 永久重定向
}

九、完整生产环境配置

1
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# /etc/nginx/sites-available/myapp
upstream app_backend {
least_conn;
server 127.0.0.1:3001 weight=3 max_fails=2 fail_timeout=15s;
server 127.0.0.1:3002 weight=2 max_fails=2 fail_timeout=15s;
keepalive 32;
}

server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}

server {
listen 443 ssl http2;
server_name example.com;

ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;

root /var/www/app;
index index.html;

access_log /var/log/nginx/app_access.log;
error_log /var/log/nginx/app_error.log;

gzip on;
gzip_types text/plain text/css application/json application/javascript;
gzip_min_length 1024;

# 请求体大小限制
client_max_body_size 10m;

# 静态资源
location ~* \.(css|js|jpg|png|gif|ico|svg|woff2)$ {
expires 30d;
add_header Cache-Control "public";
}

# API 反向代理
location /api {
proxy_pass http://app_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}

# 前端 SPA
location / {
try_files $uri $uri/ /index.html;
}
}

常见故障排查

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 1. 测试配置
nginx -t

# 2. 查看错误日志
sudo tail -f /var/log/nginx/error.log

# 3. 查看访问日志
sudo tail -f /var/log/nginx/access.log

# 4. 检查端口占用
sudo ss -tlnp | grep :80

# 5. 检查 Nginx 状态
sudo systemctl status nginx

结语

Nginx 是现代 Web 架构的核心组件,掌握它能帮你从容应对绝大多数部署场景:

  • 个人项目:静态网站 + 反向代理足够
  • 中型项目:加上负载均衡和缓存优化
  • 大型项目:配合 CDN、微服务网关

Nginx 就像瑞士军刀——功能多但每个都很实用。从静态网站开始,逐步解锁新技能。⚙️