原理见 反向代理是什么。场景:应用运行在 127.0.0.1:3000,希望通过 app.example.com 访问。
1. 确认应用在运行
curl -I http://127.0.0.1:3000
有响应再继续。
2. 创建站点配置
nano /etc/nginx/sites-available/app.example.com
server {
listen 80;
server_name app.example.com;
# 上传文件大小限制,按需调整
client_max_body_size 50m;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.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;
# WebSocket 支持
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
# 超时(长任务可加大)
proxy_read_timeout 300s;
}
}
3. 启用并重载
ln -s /etc/nginx/sites-available/app.example.com /etc/nginx/sites-enabled/
nginx -t && systemctl reload nginx
4. 解析域名并申请证书
把 app.example.com 解析到服务器 IP,然后:
certbot --nginx -d app.example.com
详见 Certbot 申请免费证书。
5. 应用只监听本机
确保应用(或 Docker 容器)只监听 127.0.0.1,避免外部绕过 Nginx 直接访问:
ss -tlnp | grep 3000
看到 127.0.0.1:3000 而不是 0.0.0.0:3000。Docker 容器发布端口写成 127.0.0.1:3000:3000。
常见问题
502 Bad Gateway:应用没运行或端口不对,见 Nginx 502 排查。
应用里拿到的 IP 都是 127.0.0.1:应用需要信任代理并读取 X-Forwarded-For,各框架都有对应设置。
WebSocket 连不上:检查 Upgrade 和 Connection 两行是否加了。
页面跳转到 http 或 127.0.0.1:应用需要读取 X-Forwarded-Proto 和 Host,或在应用配置中设置外部访问地址。
代理到子路径
想用 example.com/app/ 访问,配置会更复杂(应用需要支持子路径)。能用子域名就用子域名,省很多麻烦。
还拿不准选哪款?
把业务类型、访问人群和预算告诉我们,工程师 7×24 在线,工单平均 10 分钟内响应。
