如何在Next.js中间件中返回HTML及HTTP 410状态码?
在Next.js中间件中返回410状态码及自定义HTML
完全可行,你可以通过NextResponse的构造函数直接创建自定义响应,设置状态码、响应头和HTML内容,具体实现步骤如下:
- 导入
NextResponse和NextRequest(按需获取请求信息) - 编写自定义HTML内容字符串
- 实例化
NextResponse,传入HTML内容,同时配置410状态码和text/html类型的响应头
示例代码(middleware.ts)
import { NextResponse, NextRequest } from 'next/server'; export function middleware(request: NextRequest) { // 可根据路由或其他条件判断是否返回410 if (request.nextUrl.pathname.startsWith('/deprecated')) { const customHtml = ` <h1>Error 410</h1> <h2>Permanently deleted or Gone</h2> <p>This page is not found and is gone from this server forever</p> `; return new NextResponse(customHtml, { status: 410, headers: { 'Content-Type': 'text/html', }, }); } // 其他请求正常放行 return NextResponse.next(); } // 可选:配置中间件生效的路由规则 export const config = { matcher: ['/deprecated/:path*', '/old-page'], };
关键说明
NextResponse构造函数支持直接传入响应体内容,只要正确设置Content-Type头,浏览器就会解析为HTML- 通过配置对象的
status字段直接指定410状态码即可 - 可通过
config.matcher或请求判断逻辑,精准控制哪些路由返回410响应
内容的提问来源于stack exchange,提问作者Ali EXE
相关产品推荐
相关产品推荐

