Nginx 路径反向代理实战:多服务分发配置与排错指南(CentOS 环境)
在微服务架构中,我们常常需要将一个入口域名根据路径转发给不同的服务模块,例如用户服务、商户服务和管理后台。本文将带你从 Nginx 安装 到 路径级反向代理配置,再到 常见错误排查,一步步构建一套稳定可靠的网关层配置方案。
📦 一、Nginx 安装(基于 CentOS)
# 安装 epel 源
sudo yum install epel-release -y# 安装 nginx
sudo yum install nginx -y# 设置开机自启并启动
sudo systemctl enable nginx
sudo systemctl start nginx
🎯 二、转发目标说明(路径不变,仅转发端口)
请求路径 | 转发目标地址 |
---|---|
/userportal/** | http://127.0.0.1:8082/userportal/** |
/merchant/** | http://127.0.0.1:8083/merchant/** |
/console/** | http://127.0.0.1:8084/console/** |
例如:
http://gateway.example.com/userportal/api/profile
→http://127.0.0.1:8082/userportal/api/profile
🛠️ 三、Nginx 配置文件示例
编辑文件 /etc/nginx/conf.d/gateway.conf
:
server {listen 80;server_name gateway.example.com;location /userportal/ {proxy_pass http://127.0.0.1:8082;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;}location /merchant/ {proxy_pass http://127.0.0.1:8083;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;}location /console/ {proxy_pass http://127.0.0.1:8084;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;}# 防止未匹配路径回退到静态目录location / {return 404;}
}
特别提醒:
proxy_pass
不要加/
结尾,确保路径不被截断。- 所有子路径都会完整保留,例如
/userportal/api/**
不会被移除userportal
。
✅ 四、检查配置并重载服务
# 检查配置文件语法
sudo nginx -t# 应用修改
sudo systemctl reload nginx
🧪 五、调试和排错案例分析
✅ 情况一:请求被当作静态文件处理
错误日志:
open() "/usr/share/nginx/html/userportal/api/profile" failed (2: No such file or directory)
原因:
请求头中的 Host
与 server_name
不匹配,Nginx 默认进入了 default_server
,尝试读取静态资源。
解决办法:
- 正确设置
server_name gateway.example.com
- 调试时添加 Host 头,例如:
curl -H "Host: gateway.example.com" http://127.0.0.1/userportal/api/profile
✅ 情况二:Nginx 无法连接后端端口
错误日志:
connect() to 127.0.0.1:8082 failed (13: Permission denied)
原因:
SELinux 拒绝了 nginx 的网络请求权限。
解决方式:
# 允许 httpd 发起网络连接(推荐)
sudo setsebool -P httpd_can_network_connect 1
或(仅适用于测试环境):
sudo setenforce 0
🔥 六、防火墙放通端口(如启用 firewalld)
sudo firewall-cmd --add-port=8082/tcp --permanent
sudo firewall-cmd --add-port=8083/tcp --permanent
sudo firewall-cmd --add-port=8084/tcp --permanent
sudo firewall-cmd --reload
🧰 七、进阶建议
- 为不同服务配置 HTTPS,使用 Certbot 免费申请证书;
- 按路径拆分访问日志,便于排查;
- 可设置 URI 重写、缓存规则、限速等高级特性;
- 添加 WebSocket 支持或跨域(CORS)策略支持,适用于前后端分离架构。
✅ 总结
Nginx 是微服务架构中轻量且强大的反向代理网关工具。通过合理配置路径映射和 Host 匹配机制,我们可以轻松实现多服务转发、高性能分流以及安全隔离。本案例中不仅讲解了路径级转发的配置方法,还深入剖析了调试与 SELinux 权限问题,帮助你快速构建稳定可控的网关系统。