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

NextResponse.rewrite失效(返回空白页):维护模式实现问题排查

Next.js 中间件实现维护模式的问题排查与解决

问题现象

  • 调用 NextResponse.rewrite 跳转维护页时,网络面板显示已获取正确 HTML,但页面空白无法渲染
  • 改用 NextResponse.redirect 时,Firefox 提示「页面重定向不正确」,触发重定向循环

排查与解决过程

  1. 初始无路由匹配规则时,全局拦截所有请求导致资源加载异常与重定向循环
  2. 添加 matcher 配置后出现 SyntaxError,经检查是路由匹配规则写法有误
  3. 最终通过在匹配规则中排除特定路由,彻底解决所有问题:
    • 排除 /_next/ 路由:避免拦截 Next.js 内部静态资源、客户端脚本,解决 rewrite 后页面空白的问题
    • 排除 /api/auth/ 路由:防止认证接口被重复拦截,解决重定向循环问题
    • 排除静态资源文件(如图片、样式、脚本):确保维护页自身资源能正常加载

最终可行代码示例

middleware.ts

import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export function middleware(request: NextRequest) {
  // 从环境变量控制维护模式开关
  const isMaintenance = process.env.NEXT_PUBLIC_MAINTENANCE === 'true'
  
  if (isMaintenance) {
    return NextResponse.rewrite(new URL('/maintenance', request.url))
  }
  
  return NextResponse.next()
}

// 配置路由匹配规则,排除无需拦截的路径
export const config = {
  matcher: [
    '/((?!_next|api/auth|favicon.ico|.*\\.(png|jpg|jpeg|svg|css|js)$).*)',
  ],
}

next.config.js

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
}

module.exports = nextConfig

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 04:12:03