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

如何将Next.js中永久重定向的状态码从308改为301?

解决Next.js非www重定向返回301而非308的问题

问题背景

在next.config.js中配置非www到www的重定向时,设置permanent: true会默认返回308状态码,但需要改为301。原配置代码如下:

redirects: async () => [
  {
    source: '/:path*',
    has: [{ type: 'host', value: 'example.com' }],
    destination: 'https://www.example.com/:path*',
    permanent: true,
  },  
]

解决方案

Next.js的redirects API不支持自定义重定向状态码,permanent: true固定对应308(保留请求方法的永久重定向)。要返回301,需改用**自定义中间件(Middleware)**实现:

  1. 在项目根目录创建middleware.ts(或middleware.js)文件,写入以下代码:
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export function middleware(request: NextRequest) {
  const hostname = request.headers.get('host')

  if (hostname === 'example.com') {
    const targetUrl = new URL(request.url)
    targetUrl.hostname = 'www.example.com'
    // 明确指定返回301状态码
    return NextResponse.redirect(targetUrl, { status: 301 })
  }

  return NextResponse.next()
}

// 匹配所有路径生效
export const config = {
  matcher: '/:path*',
}
  1. 删除next.config.js中原来的redirects配置,避免冲突。

说明

中间件会在每个请求到达时执行,通过检查请求的Host头判断是否为非www域名,然后构建目标URL并返回301重定向响应,完全符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 19:10:17