使用K8s Ingress部署NextJS至子路径时遇404错误求助
问题分析与解决方案
你的404问题核心来自Ingress重写规则与NextJS basePath配置的冲突,以及路径匹配的细节问题,具体原因和修复步骤如下:
1. 核心问题:全局rewrite-target导致路径转发错误
你在Ingress全局annotations中设置了nginx.ingress.kubernetes.io/rewrite-target: /,这会让所有匹配的请求都被强制重写为根路径/转发给对应服务:
- 主路径
/重写后仍是/,所以React应用正常响应。 - 对于
/site路径,所有匹配/site前缀的请求(比如/site、/site/about)都会被重写为/转发给NextJS服务。但NextJS配置了basePath: /site,它的内部路由逻辑是剥离请求路径中的/site前缀后再处理,这种全局重写会导致NextJS无法识别子路径请求,直接返回404。
2. 修复步骤
步骤1:调整Ingress配置,设置精确的重写规则
移除全局的rewrite-target,针对/site路径使用正则匹配和精准重写:
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: simple-ingress annotations: kubernetes.io/ingress.class: 'nginx' # 针对/site路径设置重写规则:将/site(/xxx)格式的请求重写为/xxx nginx.ingress.kubernetes.io/rewrite-target: /$2 spec: tls: - hosts: - 'example.com' rules: - host: 'example.com' http: paths: - path: / pathType: Prefix backend: service: name: react-app port: number: 80 # 使用正则匹配/site开头的路径,pathType设为ImplementationSpecific以支持正则语法 - path: /site(/|$)(.*) pathType: ImplementationSpecific backend: service: name: next-app port: number: 3002
这个配置的作用:
- 访问
example.com/site→ 转发给NextJS服务的路径是/ - 访问
example.com/site/about→ 转发给NextJS服务的路径是/about
完全匹配NextJSbasePath: /site的路由处理逻辑。
步骤2:简化NextJS配置,移除冗余项
NextJS的basePath会自动处理静态资源前缀和图片路径,无需手动配置冗余项:
const nextConfig = { staticPageGenerationTimeout: 60, basePath: isProd ? '/site' : '', // 移除冗余的assetPrefix和images.path配置 } module.exports = withNx(nextConfig)
步骤3:验证NextJS构建环境
确保生产环境构建时isProd变量为true,否则basePath不会生效,导致路由不匹配。可以通过构建命令传入环境变量:
NODE_ENV=production npm run build
3. 额外检查点
- 确认NextJS服务的3002端口正常监听,且Kubernetes服务处于Running状态。
- 查看Ingress控制器日志,排查请求转发的具体路径是否符合预期。
内容的提问来源于stack exchange,提问作者dinesh
相关产品推荐
相关产品推荐

