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

Next.js 14.2.4部署Google Cloud Run后重定向功能异常求助

Next.js 14.2.4 部署到Google Cloud Run后,重定向页面部分模块无法加载

问题背景

基于Next.js 14.2.4的应用,本地和Vercel部署时重定向功能正常,但部署到Google Cloud Run后,重定向完成后部分页面模块完全无法显示和运行。重定向逻辑代码如下:

route.ts

import { NextResponse } from 'next/server'

export async function GET (request: Request) {
  const { searchParams } = new URL(request.url)
  const vacancyId = searchParams.get('vacancyId')

  if (!vacancyId) {
    return NextResponse.json({ error: 'vacancyId is required' }, { status: 400 })
  }

  // Get the original host from X-Forwarded-Host header or use a default value
  const originalHost = request.headers.get('x-forwarded-host') || 'default.host'
  const baseUrl = `https://${originalHost}`

  // Log the baseUrl and redirect URL for debugging
  console.log('Base URL:', baseUrl)

  const redirectUrl = new URL('/form/personal-info', baseUrl)
  redirectUrl.searchParams.append('vacancyId', vacancyId)

  // Log the redirect URL for debugging
  console.log('Redirecting to:', redirectUrl.toString())

  try {
    return NextResponse.redirect(redirectUrl.toString())
  } catch (error) {
    console.error('Redirect failed:', error)
    return NextResponse.json({ error: 'Failed to handle redirect' }, { status: 500 })
  }
}

核心原因

Google Cloud Run作为反向代理服务,会通过内部HTTP协议转发请求并修改请求头。Next.js默认未完全信任Cloud Run的代理头,导致生成的前端资源路径错误(比如使用内部主机名而非外部域名),最终模块加载失败。

解决方案

1. 配置Next.js信任Cloud Run代理

在next.config.js中添加以下配置,让Next.js正确识别Cloud Run发送的代理头:

/** @type {import('next').NextConfig} */
const nextConfig = {
  output: 'standalone', // Cloud Run推荐使用独立构建产物
  trustHostHeader: true, // 信任Host头
  serverRuntimeConfig: {
    trustedProxies: ['*'], // 信任所有代理(也可指定Cloud Run的具体IP段)
  },
}

module.exports = nextConfig

2. 修正重定向逻辑的协议与主机获取

不要硬写https协议,改用x-forwarded-proto头获取用户实际访问的协议;同时增加host头作为x-forwarded-host的 fallback:

// 替换原baseUrl生成代码
const protocol = request.headers.get('x-forwarded-proto') || 'https';
const originalHost = request.headers.get('x-forwarded-host') || request.headers.get('host') || 'default.host';
const baseUrl = `${protocol}://${originalHost}`;

3. 检查Cloud Run服务配置

  • 确认容器端口设置为Next.js默认的3000(或你自定义的端口)
  • 确保服务Ingress设置为All(允许外部访问)
  • 查看Cloud Run日志,检查重定向后的资源请求是否返回404,确认资源路径是否为外部域名

4. 验证前端资源加载

重定向后打开浏览器控制台的Network标签,检查加载失败的模块请求URL:

  • 正确URL应为https://你的域名/_next/static/...
  • 如果出现Cloud Run内部域名或错误协议,说明代理头配置未生效

内容的提问来源于stack exchange,提问作者Facundo Sánchez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 00:43:13