下面给你整理一份 “.NET 服务器 Kestrel 配置 Nginx 作为反向代理的问题记录(避坑指南)”,适合你做学习笔记、博客文章或 YouTube 口播技术内容。
.NET 服务器 Kestrel 配置 Nginx 作为反向代理的问题记录(避坑指南)
Kestrel 是 ASP.NET Core 默认内置的 Web 服务器,但它不负责处理静态文件、SSL、多站点等,因此生产环境一般使用 Nginx 作为反向代理。
但实际部署中,经常会踩坑。下面就是常见问题 + 解决方案总结。
一、Kestrel + Nginx 标准配置
1.1 Nginx 配置示例
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://127.0.0.1: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 Kestrel 程序监听
appsettings.json:
"Kestrel": {
"Endpoints": {
"Http": {
"Url": "http://127.0.0.1:5000"
}
}
}
二、常见问题与解决方案(真实踩坑记录)
问题 1:访问后提示 502 Bad Gateway
常见原因:
- Kestrel 根本没启动
- Kestrel 没监听 127.0.0.1:5000
- 监听的是
localhost而不是127.0.0.1(Nginx 不认) - 程序被占用端口
解决方案:
查端口:
sudo lsof -i:5000
手动测试 Kestrel:
curl http://127.0.0.1:5000
能通 → 说明是 Nginx 配置问题
不通 → 程序没启动或绑定错误
问题 2:Nginx 代理 WebSocket 失效
表现:SignalR / WebSocket 无法连接,一直报错。
原因:Nginx 默认不支持 WebSocket,需要手动开启
解决:添加以下配置
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
问题 3:Https 反代后 Request.Scheme 还是 http
例如生成 URL 时变成:
http://yourdomain.com/login
原因:未设置 X-Forwarded-Proto
解决:
Nginx:
proxy_set_header X-Forwarded-Proto $scheme;
Program.cs 加:
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedFor
});
问题 4:静态文件、图片访问不到 或 404
原因:Nginx 默认不会代理静态文件路径
解决方案 1(推荐)
让 ASP.NET Core 自己提供静态文件
Program.cs:
app.UseStaticFiles();
解决方案 2:让 Nginx 提供静态文件
location /images/ {
alias /var/www/app/images/;
}
问题 5:Nginx 返回的文件变为下载(MIME 错误)
表现:
前端访问 .json、.wasm、.js 会直接强制下载。
常见原因
缺少 MIME 配置
解决
在 nginx.conf 加:
include /etc/nginx/mime.types;
问题 6:发布后无法访问 / Kestrel 挂掉
常见原因:
- 未设置 systemd 自动启动
- 程序意外崩溃
- 权限不足
解决:创建 systemd 服务
/etc/systemd/system/kestrel-app.service
[Unit]
Description=ASP.NET App
After=network.target
[Service]
WorkingDirectory=/var/www/app
ExecStart=/usr/bin/dotnet app.dll
Restart=always
RestartSec=10
SyslogIdentifier=dotnet-app
User=www-data
Environment=ASPNETCORE_ENVIRONMENT=Production
[Install]
WantedBy=multi-user.target
启动:
sudo systemctl enable kestrel-app
sudo systemctl start kestrel-app
sudo systemctl status kestrel-app
三、Nginx 性能优化建议
1. 开启 Gzip 压缩
gzip on;
gzip_types text/plain text/css application/javascript application/json;
2. 减少代理超时
proxy_read_timeout 300;
proxy_send_timeout 300;
3. 提升文件上传限制
client_max_body_size 50M;
四、最终建议(生产环境最佳实践)
✔ Kestrel 只负责跑应用
✔ Nginx 负责:反向代理 / SSL / 负载均衡 / 静态文件
✔ 使用 systemd 自动守护应用
✔ 开启 Forwarded Headers 修正 Scheme
✔ WebSocket 必须升级 Connection 头
发表回复