在云服务器上配置 Nginx 反向代理 可以将客户端请求转发到后端服务(如 Node.js、Python、Java 应用),同时实现负载均衡、HTTPS 卸载等功能。以下是详细步骤:

1. 安装 Nginx
在云服务器上安装 Nginx(以 Ubuntu/CentOS 为例):
Ubuntu/Debian
sudo apt update sudo apt install nginx -y sudo systemctl start nginx sudo systemctl enable nginx
CentOS/RHEL
sudo yum install epel-release -y sudo yum install nginx -y sudo systemctl start nginx sudo systemctl enable nginx
2. 配置反向代理
假设后端服务运行在 127.0.0.1:3000(如 Node.js 应用),需将 80 端口的请求转发到该服务。
2.1 修改 Nginx 配置文件
编辑默认配置文件或新建一个:
sudo nano /etc/nginx/conf.d/reverse-proxy.conf
填入以下内容(根据需求调整):
server { listen 80; server_name your_domain.com; # 替换为你的域名或服务器IP location / { proxy_pass http://127.0.0.1:3000; # 转发到后端服务 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; } }
2.2 检查配置语法
sudo nginx -t # 测试配置是否正确
2.3 重启 Nginx
sudo systemctl restart nginx
3. 高级配置
3.1 负载均衡(多后端服务)
如果有多台后端服务器,可以使用 upstream 实现负载均衡:
upstream backend_servers { server 127.0.0.1:3000 weight=3; # 权重3 server 192.168.1.2:3000; # 其他后端IP server 192.168.1.3:3000 backup; # 备用服务器 } server { listen 80; server_name your_domain.com; location / { proxy_pass http://backend_servers; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } }
3.2 HTTPS 配置(Certbot 免费证书)
安装 Certbot 并签发 SSL 证书:
# Ubuntu/Debian sudo apt install certbot python3-certbot-nginx -y sudo certbot --nginx -d your_domain.com # CentOS/RHEL sudo yum install certbot python3-certbot-nginx -y sudo certbot --nginx -d your_domain.com
Certbot 会自动修改 Nginx 配置,启用 HTTPS 并强制跳转。
4. 测试反向代理
-
本地测试:
curl http://your_server_ip # 应返回后端服务的内容
-
浏览器访问:
-
打开浏览器访问
http://your_domain.com,确认请求被转发到后端。
-
5. 常见问题排查
5.1 502 Bad Gateway
-
后端服务未运行:检查后端服务是否监听
127.0.0.1:3000。 -
权限问题:确保 Nginx 用户(如
www-data)有权访问后端端口。
5.2 404 Not Found
-
proxy_pass地址错误:确认后端服务的路径和端口。 -
后端服务未配置根路由:检查后端应用是否处理
/请求。
5.3 日志分析
查看 Nginx 错误日志:
sudo tail -f /var/log/nginx/error.log
6. 安全加固
-
限制访问IP:
location / { allow 192.168.1.0/24; # 只允许特定IP段 deny all; proxy_pass http://127.0.0.1:3000; }
-
禁用敏感信息头: