我有一个Next.js博客,数据来自CMS (无头WordPress)。
假设每个帖子都有一个标题和一个id。我想为我的博客创建简短的链接,这样每个site.com/blog/[id] (或site.com/blog/?id=[id])都会自动重定向到site.com/blog/[title]。而且,它应该是动态的;因此,每次创建新的帖子时,都应该生成短链接。
我有点搞不懂怎么做。我应该在每个岗位上做吗?应该在Next.js配置中定义重定向/重写吗?我应该在服务器端这样做吗,就像使用.htaccess一样?是重定向还是重写?
也是在GitHub讨论中:https://github.com/vercel/next.js/discussions/39897
发布于 2022-08-28 23:20:15
您可以使用Next.js 中间件动态地将短URL重定向到它们的长URL对应方。
与在构建时生成的redirects不同,中间件运行在每个请求上,允许将新创建的页面重定向到。
在与middleware.js文件夹相同的级别添加以下pages文件。
// middleware.js
import { NextResponse } from 'next/server';
import getTitleById from '<path-to-getTitleById>'; // Replace with your own function
export function middleware(req) {
// Check if path matches short URL (`/b?id=1` or `b/1`)
if (req.nextUrl.pathname === '/b' || req.nextUrl.pathname.startsWith('/b/')) {
// Get `id` from URL path or query parameter
const [,,idFromPath] = req.nextUrl.pathname.split('/');
const id = idFromPath ?? req.nextUrl.searchParams.get('id');
const title = getTitleById(id);
// If a `title` for given `id` exists, redirect to `/blog/[title]` page
if (title) {
return NextResponse.redirect(new URL(`/blog/${title}`, req.url));
}
}
return NextResponse.next();
}上面的URL(如/b?id=1或/b/1 )将重定向到适当的/blog/slug-for-id-1,因为getTitleById能够执行该映射。
https://stackoverflow.com/questions/73454653
复制相似问题