static - Next.js:我们如何将动态路由重定向到静态页面?
问题描述
使用 Next.js ,我目前有一个带有 /pages/[...slug]/index.ts 形式的单一入口点的应用程序
它包含一个 getServerSideProps 函数,该函数分析 slug 并决定重定向
在某些情况下需要重定向,但它总是指向可以静态呈现的页面。示例:将 /fr/uid 重定向到可以是静态的 /fr/blog/uid。在其他情况下,slug 已经是可以是静态的页面的 url。
如何将此动态元素与所有页面的静态生成混合?
非常感谢你的帮助!
解决方案
如果您使用的是 AWS CloudFront,则可以使用CloudFront Functions进行重定向。
CloudFront Functions 非常适合用于以下用例的轻量级、短时间运行的函数:
- URL 重定向或重写——您可以根据请求中的信息将查看者重定向到其他页面,或者将所有请求从一条路径重写到另一条路径。
当 NextJS 页面被移动或删除时,这是我们用来将客户端(例如 Native App、Google 搜索索引等)重定向到新位置的方法。
// NOTE: Choose "viewer request" for event trigger when you associate this function with CloudFront distribution.
function makeRedirectResponse(location) {
var response = {
statusCode: 301,
statusDescription: 'Moved Permanently',
headers: {
'location': { value: location }
}
};
return response;
}
function handler(event) {
var mappings = [
{ from: "/products/decode/app.html", to: '/products/decode.html' },
{ from: "/products/decode/privacy/2021_01_25.html", to: '/products/decode/privacy.html' }
];
var request = event.request;
var uri = request.uri;
for (var i = 0; i < mappings.length; i++) {
var mapping = mappings[i]
if (mapping.from === uri) {
return makeRedirectResponse(mapping.to)
}
}
return request;
}
推荐阅读
- java - 如何将反应流连接到 quarkus / smallrye 中的 AMQP 代理
- android - 适用于 Android 8.0.0 的 Ionic 3 - net::ERR_CONNECTION_REFUSED (http://localhost:8080/)
- javascript - 错误:发送后无法设置标头 - 正确处理快速控制器中的错误
- tf.keras - 当keras使用float32的dtype调用numpy.asarray时如何修复“float()参数必须是字符串或数字,而不是'PngImageFile”错误
- javascript - Javascript Array unshift new Date 减去 1 天
- javascript - 通过他们的 API 将多张图片上传到 Imgur
- filter - 有没有办法用另一列的条件过滤和返回唯一列的结果?
- arrays - 使用 PowerShell 和 Linq 在数组中选择不同的项目
- llvm - 与 ld.lld 链接的 LLVM 字节码给出分段错误
- matlab - 更改 MATLAB 频谱图的轴单位