如何配置ASP.NET Core适配Kubernetes NGINX Ingress解决静态资源404问题
解决方案
根因说明
你遇到的问题本质是两层不匹配:
- 前端页面输出的静态资源引用为根路径绝对路径,没有携带
/webui前缀,导致请求直接发到test.local/css/xxx,匹配不到Ingress的/webui规则返回404 - ASP.NET Core的静态文件服务和路由渲染没有完整适配子路径部署的场景
步骤1:修正Ingress配置,添加必要注解
在Ingress的metadata.annotations下添加两个配置,让Nginx转发请求时传递路径前缀信息:
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: test namespace: test annotations: nginx.ingress.kubernetes.io/use-regex: "true" nginx.ingress.kubernetes.io/x-forwarded-prefix: "/webui" spec: ingressClassName: nginx rules: - host: "test.local" http: paths: - path: /api pathType: Prefix backend: service: name: api port: number: 80 - path: /webui pathType: Prefix backend: service: name: webui port: number: 80
步骤2:完善ASP.NET Core的子路径适配配置
修改Startup.cs,补充转发头处理、静态文件前缀配置和Razor路由适配:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace rmn.WebUI { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddRazorPages() // 让Razor渲染的所有链接自动携带PathBase前缀 .AddRazorPagesOptions(options => { options.RoutePrefix = string.Empty; }); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // 优先处理Nginx传递的转发头,识别外部路径前缀、协议等信息 app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.All }); app.UsePathBase("/webui"); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } // 给静态文件指定匹配前缀,确保带/webui的静态资源请求能被正确处理 app.UseStaticFiles(new StaticFileOptions { RequestPath = "/webui" }); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } } }
步骤3:修正前端资源引用方式
把页面里所有绝对路径开头的资源引用(比如/css/style.css、/js/app.js)改成以下两种写法之一:
- 相对路径写法:
css/style.css(去掉开头的/) - Razor标签助手写法:
<link rel="stylesheet" href="~/css/style.css" />(~/开头会自动拼接配置好的/webui前缀)
内容的提问来源于stack exchange,提问作者Bigpodgurc
相关产品推荐
相关产品推荐

