gpt4 book ai didi

amazon-web-services - Amazon CloudFront 中的 NextJS 动态路由

转载 作者:行者123 更新时间:2023-12-03 08:13:31 24 4
gpt4 key购买 nike

我有一个使用 NextJS 作为包装器的应用程序,并且我使用 NextJS's dynamic routing feature 。由于dns.com/path/page,我在将其部署到CloudFront时遇到了问题没有被渲染,而是 CloudFront 期望它是 dns.com/path/page.html 。我通过应用这个 lambda-edge-nice-url 解决了这个问题解决方案。现在可以正常工作了。然而,仍然存在一个问题:NextJS 的动态路由。 dsn.com/path/subpath/123应该可以,因为 123 是一个动态参数。然而,这不起作用。仅当我访问 dns.com/path/subpath/[id] 时才返回页面,这当然是不正确的,因为 [id] 不是我想要加载的参数。

最奇怪的是:如果我尝试直接访问上面所说的 URL,就会失败。但是,在应用程序内部,我有可以重定向用户的按钮和链接,并且可以正常工作。

从应用程序内部导航(回调中带有 router.push 的按钮): enter image description here

尝试直接访问网址: enter image description here

有人可以帮助我正确路由请求吗?

最佳答案

我使用 CloudFront Lambda@Edge 源请求函数来处理将动态路由和静态路由重写到适当的 HTML 文件,以便 CloudFront 可以为任何路径提供预期文件。

我的 lambda 函数看起来像

export const handler: CloudFrontRequestHandler = async (event) => {
const eventRecord = event.Records[0];
const request = eventRecord.cf.request;
const uri = request.uri;

// handle /posts/[id] dynamic route
if (uri === '/posts' || uri.startsWith('/posts/')) {
request.uri = "/posts/[id].html";
return request;
}

// if URI includes ".", indicates file extension, return early and don't modify URI
if (uri.includes('.')) {
return request;
}

// if URI ends with "/" slash, then we need to remove the slash first before appending .html
if (uri.endsWith('/')) {
request.uri = request.uri.substring(0, request.uri.length - 1);
}

request.uri += '.html';
return request;
};

关于amazon-web-services - Amazon CloudFront 中的 NextJS 动态路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70096145/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com