Reputation: 1339
I want to transfer my blog from Jekyll to NextJS and looking how to specify custom URLs. I followed the official NextJS guide on their website, but the routing part was relatively simple. From docs, I got that URLs are based on folders/files structure, but I want to have a subfolder per site topic in the pages folder but keep URLs flat. Something like that:
https://example.com/how-to-start-investing
<- no investing folder in URL)https://example.com/how-to-upgrade-ubuntu
<- no devops folder in URL)In Jekyll, I used Front Matter to specify a custom URL per page. In NextJS looks like I have to use rewrites, but is there any other option? Also Link component has an attribute to change the link URL, but this is just to display links with URLs.
Upvotes: 2
Views: 2082
Reputation: 1339
Finally got it to work, so in order to use custom URLs, I have to combine rewrites with redirects, the latter needed for SEO.
Without redirects, I can just use the canonical tag to tell Google my preferred URL, but technically the same article keeps on being available using two URLs, in my case:
So the final next.config.js is:
module.exports = {
async rewrites() {
return [
{
source: '/how-to-start-investing',
destination: '/investing/how-to-start-investing'
}
]
},
async redirects() {
return [
{
source: '/investing/how-to-start-investing',
destination: '/how-to-start-investing',
permanent: true
}
]
}
}
And this is to be repeated for all URLs.
Upvotes: 3
Reputation: 2388
In NextJS, routes are defined by the structure of the pages directory. If you don't want that, you're going to have to work around that feature. Some options you have:
/how-to-start-investing/
to /investing/...
— note that unlike redirects, rewrites don't expose the destination path, so the user will stay on /how-to-start-investing/
url.how-to-start-investing.js
). Inside the file, export another component, for example:// how-to-start-investing.js
import { HowToStartInvesting } from "../components/investing/HowToStartInvesting";
export default HowToStartInvesting;
If you use this approach, I suggest you put your components somewhere outside the pages directory, so you don't have two urls for the same component.
Upvotes: 3