You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core MVC部署K8s:Nginx Ingress重写后静态文件前缀问题

ASP.NET Core MVC部署K8s Nginx Ingress后静态文件与路径前缀问题解决

静态文件请求前缀配置

在Program.cs中修改静态文件服务配置,指定Ingress的路径前缀作为静态文件的请求入口:

builder.Services.AddStaticFiles(options =>
{
    // 对应Ingress配置的/custom/path前缀
    options.RequestPath = "/custom/path";
});

这样项目中wwwroot下的静态资源(如css、js、图片),就能通过www.example.com/custom/path/xxx的路径正确访问。

MVC路由前缀配置

同时要给控制器路由加上统一前缀,确保页面中生成的URL自动带上前缀:

app.UseRouting();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        // 把/custom/path加入路由规则开头
        pattern: "custom/path/{controller=Home}/{action=Index}/{id?}");
});

这样使用Url.Action生成的链接(比如页面中的<a>标签)会自动包含前缀,配合_Layout.cshtml里的base标签,就能避免直接请求根路径导致的404。

验证Base标签配置

确认_Layout.cshtml中的base标签末尾带有斜杠,确保相对路径拼接正确:

<base href="/custom/path/" />

Ingress Rewrite规则检查

确保你的Nginx Ingress rewrite规则正确,将/custom/path/xxx重写为应用内部的/xxx:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$1
    nginx.ingress.kubernetes.io/use-regex: "true"
spec:
  rules:
  - host: www.example.com
    http:
      paths:
      - path: /custom/path/(.*)
        pathType: Prefix
        backend:
          service:
            name: your-app-service-name
            port:
              number: 80

内容的提问来源于stack exchange,提问作者song2park

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 02:47:38