同一服务器通过子域名部署多个.NET Core项目的Nginx配置问题
Nginx 子域名映射多.NET Core 项目配置方案
前提确认
首先确认你的三个.NET Core项目均已配置为后台运行(推荐使用systemd管理服务),且各自监听不同的本地端口,示例端口假设如下,可替换为你实际的端口:
- www.example.com 对应项目监听
localhost:5000 - api1.example.com 对应项目监听
localhost:5001 - api2.example.com 对应项目监听
localhost:5002
步骤1:编写Nginx站点配置
如果你用的是Debian/Ubuntu系统,建议将每个站点的配置单独存放在 /etc/nginx/sites-available/ 目录下,配置完成后软链接到 /etc/nginx/sites-enabled/ 目录生效;如果是RHEL/CentOS系统,直接在 /etc/nginx/conf.d/ 目录下创建.conf后缀的配置文件即可。
1.1 www.example.com 配置示例
创建文件 /etc/nginx/sites-available/www.example.com,内容如下:
server { listen 80; server_name www.example.com; location / { proxy_pass http://localhost:5000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection keep-alive; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } }
1.2 api1.example.com 配置示例
创建文件 /etc/nginx/sites-available/api1.example.com,内容如下:
server { listen 80; server_name api1.example.com; location / { proxy_pass http://localhost:5001; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection keep-alive; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } }
1.3 api2.example.com 配置示例
创建文件 /etc/nginx/sites-available/api2.example.com,内容如下:
server { listen 80; server_name api2.example.com; location / { proxy_pass http://localhost:5002; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection keep-alive; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } }
步骤2:生效配置(Debian/Ubuntu 环境)
执行以下命令创建软链接启用站点配置:
ln -s /etc/nginx/sites-available/www.example.com /etc/nginx/sites-enabled/ ln -s /etc/nginx/sites-available/api1.example.com /etc/nginx/sites-enabled/ ln -s /etc/nginx/sites-available/api2.example.com /etc/nginx/sites-enabled/
步骤3:验证配置并重载Nginx
首先执行命令验证配置语法是否正确:
nginx -t
如果输出显示 test is successful,则执行重载命令让配置生效:
systemctl reload nginx
.NET Core 项目必要配置
需要在项目的启动代码中添加转发头支持,否则项目会无法正确获取客户端请求的域名、协议等信息。
以.NET 6+ 的Program.cs为例,添加以下代码:
builder.Services.Configure<ForwardedHeadersOptions>(options => { options.ForwardedHeaders = Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.All; options.KnownProxies.Add(IPAddress.Parse("127.0.0.1")); }); // 注意这行要放在UseAuthentication、UseAuthorization等中间件之前 app.UseForwardedHeaders();
修改后重新编译发布项目,重启对应的systemd服务即可。
常见问题排查
- 确认所有域名的DNS解析已经正确指向你的服务器公网IP
- 确认服务器防火墙/安全组已经开放80(HTTP)、443(HTTPS)端口的入站规则
- 执行
ss -tulpn确认三个.NET Core项目的端口都处于正常监听状态 - 如仍然访问异常,可查看Nginx错误日志定位问题,日志默认路径为
/var/log/nginx/error.log
内容的提问来源于stack exchange,提问作者Badr Douah
相关产品推荐
相关产品推荐

