首页 > 解决方案 > Next.js:我们如何将动态路由重定向到静态页面?

问题描述

使用 Next.js ,我目前有一个带有 /pages/[...slug]/index.ts 形式的单一入口点的应用程序

它包含一个 getServerSideProps 函数,该函数分析 slug 并决定重定向

在某些情况下需要重定向,但它总是指向可以静态呈现的页面。示例:将 /fr/uid 重定向到可以是静态的 /fr/blog/uid。在其他情况下,slug 已经是可以是静态的页面的 url。

如何将此动态元素与所有页面的静态生成混合?

非常感谢你的帮助!

标签: staticrenderingnext.jsurl-routinggetstaticprops

解决方案


如果您使用的是 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;
}

推荐阅读