Nginx 配置从入门到实践——反向代理、SSL 与负载均衡

Nginx 配置从入门到实践——反向代理、SSL 与负载均衡

作者: CaoZH
日期: 2023-08-15
本文为原创教程


Nginx 是 2023 年使用率最高的 Web 服务器(根据 Netcraft 统计,市占率超过 30%)。无论是部署前端项目、反向代理后端 API,还是配置 HTTPS,Nginx 都是必须掌握的技能。

本文从安装开始,覆盖日常开发中最常用的 Nginx 配置场景。

一、安装 Nginx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Ubuntu/Debian
sudo apt update
sudo apt install -y nginx

# CentOS
sudo yum install -y nginx

# 验证安装
nginx -v

# 启动
sudo systemctl start nginx
sudo systemctl enable nginx

# 查看状态
sudo systemctl status nginx

安装后访问 http://服务器IP,看到 Nginx 欢迎页即成功。

二、Nginx 核心概念

配置文件结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# /etc/nginx/nginx.conf — 主配置文件

user www-data; # 运行用户
worker_processes auto; # 工作进程数(通常 = CPU 核心数)

events {
worker_connections 1024; # 每个进程最大连接数
}

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

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

include /etc/nginx/conf.d/*.conf; # 站点配置
include /etc/nginx/sites-enabled/*;
}

常用目录

目录 说明
/etc/nginx/nginx.conf 主配置文件
/etc/nginx/sites-available/ 站点配置(可用)
/etc/nginx/sites-enabled/ 站点配置(启用)
/etc/nginx/conf.d/ 额外的配置片段
/var/log/nginx/access.log 访问日志
/var/log/nginx/error.log 错误日志

三、场景一:部署静态网站

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# /etc/nginx/sites-available/my-site
server {
listen 80;
server_name my-site.com www.my-site.com;
root /var/www/my-site;
index index.html;

location / {
try_files $uri $uri/ /index.html;
}

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

启用站点:

1
2
3
sudo ln -s /etc/nginx/sites-available/my-site /etc/nginx/sites-enabled/
sudo nginx -t # 测试配置
sudo systemctl reload nginx # 重载配置不中断服务

四、场景二:反向代理

/api/ 的请求转发到后端 Spring Boot 应用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
server {
listen 80;
server_name api.my-site.com;

location /api/ {
proxy_pass http://127.0.0.1:8080/; # 注意结尾斜杠
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;

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

WebSocket 代理

1
2
3
4
5
6
7
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;
}

五、场景三:配置 HTTPS(SSL)

使用 Certbot 自动申请 Let’s Encrypt 证书

1
2
3
4
5
6
7
8
# 安装 Certbot
sudo apt install -y certbot python3-certbot-nginx

# 自动申请并配置 SSL
sudo certbot --nginx -d my-site.com -d www.my-site.com

# 测试自动续期
sudo certbot renew --dry-run

手动配置 SSL

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
server {
listen 443 ssl http2;
server_name my-site.com;

ssl_certificate /etc/nginx/ssl/my-site.com.pem;
ssl_certificate_key /etc/nginx/ssl/my-site.com.key;

# SSL 安全配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
ssl_prefer_server_ciphers on;
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:50m;

# HSTS(强制 HTTPS)
add_header Strict-Transport-Security "max-age=31536000" always;

root /var/www/my-site;
index index.html;

location / {
try_files $uri $uri/ /index.html;
}
}

# HTTP 重定向到 HTTPS
server {
listen 80;
server_name my-site.com www.my-site.com;
return 301 https://$server_name$request_uri;
}

六、场景四:负载均衡

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
upstream backend {
# 轮询(默认)
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
}

# 带权重的轮询
upstream weighted {
server 192.168.1.10:8080 weight=3; # 权重3
server 192.168.1.11:8080 weight=2;
server 192.168.1.12:8080 weight=1;
}

# IP Hash(同一IP始终访问同一台服务器)
upstream ip_hash_backend {
ip_hash;
server 192.168.1.10:8080;
server 192.168.1.11:8080;
}

# 最少连接数
upstream least_conn_backend {
least_conn;
server 192.168.1.10:8080;
server 192.168.1.11:8080;
}

server {
listen 80;
server_name app.my-site.com;

location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}

七、场景五:常用的安全与性能配置

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
# 限制请求速率(防刷)
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;

server {
# 安全头
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;

# 隐藏 Nginx 版本
server_tokens off;

# 限制上传大小
client_max_body_size 10M;

# Gzip 压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml;
gzip_min_length 1000;
gzip_vary on;

location /api/ {
limit_req zone=api burst=20 nodelay; # 限速
proxy_pass http://127.0.0.1:8080;
}

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

八、排错常用命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 检查配置语法
nginx -t

# 查看配置
nginx -T

# 重载配置(优雅,不中断服务)
sudo systemctl reload nginx

# 重启
sudo systemctl restart nginx

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

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

# 测试端口监听
ss -tlnp | grep 80
ss -tlnp | grep 443

九、总结

通过本教程,你学会了 Nginx 的 5 个核心场景配置:

场景 配置要点
✅ 静态网站 root + try_files
✅ 反向代理 proxy_pass
✅ HTTPS certbot + ssl 配置
✅ 负载均衡 upstream 多种策略
✅ 安全加固 安全头 + 限速 + Gzip

一手掌握 Nginx,运维不再求人。


首发于 CaoZH 的笔记