I want the routes to work in a way that:
- Visiting
www.example.com/blog/12345
should redirect towww.example.com/blog/12345/this-is-a-test
. - Visiting
www.example.com/blog/12345/this-a-some-random-text-blahblahblah
should also redirect towww.example.com/blog/12345/this-is-a-test
. - Visiting
www.example.com/blog/12345/this-a-some-random-text-blahblahb/test/having-fun
should be 404 error.
The correct blog is always fetched using id
, and the title of the blog is set as the second parameter in the URI based on the fetched data.
Right now, for this route:
www.example.com/blog/12345/this-is-a-test
I have this folder structure in the app/
directory:
app/
blog/
[id]/
[title]/
page.tsx
From the blog/[id]/[title]/page.tsx
file, I have access to both the id
and title
. Using the id
, I can fetch and display some data. No problem, I don't need to use the title
. The title
is for SEO purposes, and I want to be able to change the title
in the URI to the actual title of the resource after being fetched using id
.
How do I achieve this? I may have to change the folder structure, but I'm not sure.
Something like this should work:
Refer: https://nextjs.org/docs/app/api-reference/functions/redirect, https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes
PS: might wanna make title optional if you want to handle
example.com/blog/12345
too.