Nginx配置与反向代理实战

一、Nginx是什么?

Nginx是一个高性能的HTTP服务器和反向代理服务器,以高并发、低内存占用著称。

1.1 Nginx能做什么?

功能 说明
HTTP服务器 静态文件服务、Vue/React前端部署
反向代理 隐藏后端服务、负载均衡
SSL/TLS HTTPS支持
静态资源缓存 加速资源访问
限流 防止DDoS攻击
gzip压缩 减少传输体积

1.2 Nginx vs Apache

特性 Nginx Apache
性能 高并发强 一般
内存占用 较高
配置文件 简洁 复杂
异步非阻塞
动态模块 不支持 支持

二、安装Nginx

2.1 Ubuntu/Debian安装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 更新apt源
sudo apt update

# 安装Nginx
sudo apt install -y nginx

# 启动Nginx
sudo systemctl start nginx
sudo systemctl enable nginx # 开机自启

# 检查状态
sudo systemctl status nginx

# 测试访问
curl http://localhost
# 应该返回Nginx欢迎页面

2.2 Docker安装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 拉取镜像
docker pull nginx:alpine

# 运行Nginx容器
docker run -d \
--name nginx-server \
-p 80:80 \
-v ~/nginx/html:/usr/share/nginx/html \
nginx:alpine

# 挂载配置文件
docker run -d \
--name nginx-server \
-p 80:80 \
-v ~/nginx/nginx.conf:/etc/nginx/nginx.conf:ro \
-v ~/nginx/html:/usr/share/nginx/html \
nginx:alpine

2.3 目录结构

1
2
3
4
5
6
7
8
9
10
11
12
# 主要目录
/etc/nginx/ # 配置目录
├── nginx.conf # 主配置文件
├── conf.d/ # 子配置目录
├── sites-available/ # 可用站点
├── sites-enabled/ # 启用站点(软链接)
└── logs/ # 日志目录
├── access.log # 访问日志
└── error.log # 错误日志

/usr/share/nginx/html/ # 默认网站目录
/var/log/nginx/ # 日志目录

三、Nginx基本配置

3.1 最小配置

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
# /etc/nginx/nginx.conf
user www-data;
worker_processes auto;
pid /run/nginx.pid;

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

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"';

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

# 性能优化
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;

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

# 包含子配置
include /etc/nginx/conf.d/*.conf;
}

3.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
# /etc/nginx/conf.d/example.conf

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

# 网站根目录
root /var/www/html;
index index.html index.htm;

# 访问日志
access_log /var/log/nginx/example_access.log;
error_log /var/log/nginx/example_error.log;

# 默认路由
location / {
try_files $uri $uri/ /index.html;
}

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

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

四、反向代理配置

4.1 什么是反向代理?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
┌─────────────────────────────────────────────────────────────────┐
│ 正向代理(VPN) │
├─────────────────────────────────────────────────────────────────┤
│ │
│ 用户 → 代理服务器 → 目标网站 │
│ (客户端知道代理) │
│ │
└─────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────┐
│ 反向代理 │
├─────────────────────────────────────────────────────────────────┤
│ │
│ 用户 → Nginx反向代理 → 后端服务器1
│ ↘ → 后端服务器2
│ ↘ → 后端服务器3
│ │
│ (用户不知道后端服务器存在) │
│ │
└─────────────────────────────────────────────────────────────────┘

4.2 基础反向代理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 反向代理配置
server {
listen 80;
server_name api.example.com;

location / {
# 代理到后端服务
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 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
}

4.3 代理到多个后端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 负载均衡配置
upstream backend {
server 127.0.0.1:8080 weight=3; # 默认权重1
server 127.0.0.1:8081 weight=1;
server 127.0.0.1:8082 backup; # 备用服务器
}

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

location / {
proxy_pass http://backend;

proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}

4.4 负载均衡策略

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
# 轮询(默认)
upstream roundRobin {
server 127.0.0.1:8080;
server 127.0.0.1:8081;
}

# 权重轮询
upstream weighted {
server 127.0.0.1:8080 weight=5; # 5/6的请求
server 127.0.0.1:8081 weight=1; # 1/6的请求
}

# IP哈希(同一IP访问同一服务器)
upstream ipHash {
ip_hash;
server 127.0.0.1:8080;
server 127.0.0.1:8081;
}

# 最少连接
upstream leastConn {
least_conn;
server 127.0.0.1:8080;
server 127.0.0.1:8081;
}

五、HTTPS配置

5.1 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
32
33
34
35
36
# HTTP重定向到HTTPS
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$server_name$request_uri;
}

# HTTPS配置
server {
listen 443 ssl http2;
server_name example.com www.example.com;

# SSL证书
ssl_certificate /etc/nginx/ssl/example.com.crt;
ssl_certificate_key /etc/nginx/ssl/example.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 off;

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

# OCSP stapling
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 8.8.4.4 valid=300s;

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

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

5.2 免费SSL证书(Let’s Encrypt)

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

# 生成证书(需要域名解析到服务器)
sudo certbot --nginx -d example.com -d www.example.com

# 自动续期(Let's Encrypt证书90天过期)
sudo certbot renew --dry-run

六、静态资源优化

6.1 静态文件缓存

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 static.example.com;
root /var/www/static;

# 图片缓存1年
location ~* \.(jpg|jpeg|png|gif|ico|svg|webp)$ {
expires 1y;
add_header Cache-Control "public, no-transform";
}

# CSS/JS缓存1个月
location ~* \.(css|js)$ {
expires 30d;
add_header Cache-Control "public";
}

# 字体缓存1年
location ~* \.(woff|woff2|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public";
}

# 禁用日志
access_log off;
}

6.2 gzip压缩

1
2
3
4
5
6
7
8
http {
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_min_length 1024;
gzip_types text/plain text/css text/xml application/json application/javascript application/xml+rss application/atom+image/svg+xml;
}

6.3 防盗链

1
2
3
4
5
6
7
8
9
location ~* \.(jpg|jpeg|png|gif|ico|mp4|mp3)$ {
valid_referers none blocked example.com www.example.com;

if ($invalid_referer) {
# 返回403或一张警告图
return 403;
# rewrite ^ /warning.jpg break;
}
}

七、实战案例

7.1 Vue/React前端部署

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 www.example.com;
root /var/www/dist; # 前端构建输出目录
index index.html;

# 防止刷新404
location / {
try_files $uri $uri/ /index.html;
}

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

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

# 访问日志
access_log /var/log/nginx/vue_access.log;
error_log /var/log/nginx/vue_error.log;
}

7.2 Node.js API代理

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
# 前端静态
server {
listen 80;
server_name example.com;
root /var/www/dist;

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

# API反向代理
server {
listen 80;
server_name api.example.com;

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

proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
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_cache_bypass $http_upgrade;
}
}

7.3 多个子域名配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 主站点
server {
listen 80;
server_name example.com www.example.com;
root /var/www/html;
# ...
}

# 子站点1 - 博客
server {
listen 80;
server_name blog.example.com;
root /var/www/blog;
# ...
}

# 子站点2 - API
server {
listen 80;
server_name api.example.com;
root /var/www/api;
# ...
}

7.4 WebSocket代理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
upstream websocket {
server 127.0.0.1:8080;
}

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

location / {
proxy_pass http://websocket;

proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_read_timeout 86400;
}
}

7.5 限流配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 限流配置
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;

server {
location /api/ {
# 每秒10个请求,burst允许突发20个
limit_req zone=api_limit burst=20 nodelay;

proxy_pass http://127.0.0.1:8080;
# ...
}
}

# 连接数限制
limit_conn_zone $binary_remote_addr zone=addr_limit:10m;

server {
location / {
limit_conn addr_limit 10;
# ...
}
}

八、常用命令

8.1 Nginx命令

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

# 重新加载配置(不中断服务)
sudo nginx -s reload

# 停止Nginx
sudo nginx -s stop

# 优雅停止(处理完请求)
sudo nginx -s quit

# 强制重载
sudo systemctl restart nginx

# 查看进程
ps aux | grep nginx

# 实时查看日志
tail -f /var/log/nginx/access.log
tail -f /var/log/nginx/error.log

8.2 日志分析

1
2
3
4
5
6
7
8
9
10
11
# 统计IP访问量
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -10

# 统计页面访问量
awk '{print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -10

# 统计HTTP状态码
awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c | sort -rn

# 统计流量
awk '{sum+=$10} END {print sum/1024/1024 " MB"}' /var/log/nginx/access.log

九、常见问题

9.1 403 Forbidden

1
2
3
4
5
6
7
8
9
10
# 解决方法:
# 1. 检查文件权限
sudo chmod -R 755 /var/www/html
sudo chown -R www-data:www-data /var/www/html

# 2. 检查index指令
index index.html index.htm;

# 3. 检查SELinux(CentOS)
setsebool -P httpd_read_user_content 1

9.2 502 Bad Gateway

1
2
3
4
5
6
7
# 解决方法:
# 1. 检查后端服务是否启动
ps aux | grep node
# 2. 检查端口是否监听
netstat -tlnp | grep 8080
# 3. 检查Nginx错误日志
tail -f /var/log/nginx/error.log

9.3 413 Request Entity Too Large

1
2
# 解决方法:在nginx.conf中添加
client_max_body_size 20M;

十、性能优化建议

优化项 配置 说明
worker进程数 worker_processes auto; 设为CPU核心数
连接数 worker_connections 4096; 提高并发
打开文件数 worker_rlimit_nofile 65535; 避免too many open files
TCP优化 tcp_nopush on; tcp_nodelay on; 减少网络延迟
缓存 open_file_cache max=65535; 缓存文件元数据
压缩 gzip on; 减少传输体积
静态资源 启用缓存 减少重复请求

参考资料


持续更新中…欢迎收藏!

#Nginx #反向代理 #负载均衡 #Web服务器 #教程


Nginx配置与反向代理实战
https://r0f2.my/post/23-nginx-reverse-proxy-lb/
作者
JA
发布于
2026年2月13日
许可协议