Nginx反向代理从入门到精通
Nginx是当今最流行的Web服务器之一。本文通过循序渐进的教程,带你从零开始搭建Nginx反向代理环境。
第1步:理解Nginx架构
Nginx采用Master+Worker多进程架构:
# 查看Nginx进程结构 $ ps aux | grep nginx root 1234 0.0 0.1 ... nginx: master process /usr/sbin/nginx www-data 1235 0.0 0.2 ... nginx: worker process www-data 1236 0.0 0.2 ... nginx: worker process www-data 1237 0.0 0.2 ... nginx: worker process www-data 1238 0.0 0.2 ... nginx: worker process # Master进程:读取配置、管理Worker # Worker进程:实际处理请求(通常等于CPU核心数)
这种异步非阻塞架构让Nginx能同时处理数万并发连接。
第2步:安装Nginx
# Ubuntu/Debian sudo apt update sudo apt install nginx # CentOS/RHEL sudo yum install epel-release sudo yum install nginx # 验证安装 nginx -v sudo systemctl start nginx sudo systemctl enable nginx # 访问测试 curl http://localhost # 应该看到Nginx欢迎页面
第3步:配置反向代理
假设后端应用运行在127.0.0.1:3000:
# 创建配置文件
sudo nano /etc/nginx/sites-available/myapp
# 写入以下内容:
server {
# 监听80端口,处理api.example.com的请求
listen 80;
server_name api.example.com;
# 访问日志配置
access_log /var/log/nginx/myapp.access.log;
error_log /var/log/nginx/myapp.error.log;
# 反向代理配置
location / {
# 转发到后端应用
proxy_pass http://127.0.0.1:3000;
# 关键:透传客户端真实IP
# 否则后端只能看到Nginx的IP(127.0.0.1)
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 10s; # 连接超时
proxy_send_timeout 60s; # 发送超时
proxy_read_timeout 60s; # 读取响应超时
}
# 静态文件直接由Nginx处理(不走代理)
location /static/ {
# alias指定静态文件根目录
alias /var/www/myapp/static/;
# 缓存30天
expires 30d;
add_header Cache-Control "public, immutable";
}
}
第4步:启用配置并测试
# 创建软链接启用站点 sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/ # 测试配置语法(重要!) sudo nginx -t # 输出:nginx: configuration file /etc/nginx/nginx.conf test is successful # 重载配置(不中断现有连接) sudo nginx -s reload
第5步:配置HTTPS
# 使用Certbot免费申请Let's Encrypt证书 sudo apt install certbot python3-certbot-nginx # 自动配置HTTPS sudo certbot --nginx -d api.example.com # 证书会自动续期,查看定时任务 sudo systemctl status certbot.timer
第6步:性能优化
# /etc/nginx/nginx.conf 优化配置
worker_processes auto; # 自动匹配CPU核心数
worker_connections 4096; # 每个Worker最大连接数
# 启用gzip压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript;
# 开启长连接(减少TCP握手开销)
upstream backend {
server 127.0.0.1:3000;
keepalive 32; # 保持32个长连接
}
常见问题排查
| 错误 | 原因 | 解决 |
|---|---|---|
| 502 Bad Gateway | 后端服务未启动 | 检查应用进程:ps aux | grep node |
| 504 Gateway Timeout | 后端处理太慢 | 增加proxy_read_timeout |
| 403 Forbidden | 静态文件权限问题 | chown -R www-data:www-data /var/www |
总结
Nginx配置记住三点:配置完先nginx -t测试、用nginx -s reload热重载、日志是排查问题的关键。
