Changing posts path
hayschan opened this issue · comments
The current post path is https://website-name.com/posts/
. Is there a way I could change it to https://website-name.com/
?
For example, from https://website-name.com/posts/test-post
to https://website-name.com/test-post
.
As my previous blog uses this post structure, I would like to retain the post structure for consistent SEO result.
For future fellows that comes accross this post, here is what I have done to solve this issue.
To change the path of the posts from https://website-name.com/posts/test-post
to https://website-name.com/test-post
, you need to make the following changes to the index.js
, slug.js
, and next.config.js
files.
index.js
In the index.js
file, you need to update the Link
component's href
and as
props as follows.
Before:
nextjs-blog-theme/pages/index.js
Lines 26 to 29 in b23a583
After:
<Link
as={post.filePath.replace(/\.mdx?$/, '')}
href={`/${post.filePath.replace(/\.mdx?$/, '')}`}
>
slug.js
In the slug.js
file, you need to update the Link
components' href
prop as follows:
Before:
After:
{prevPost && (
<Link href={`/${prevPost.slug}`}>
{nextPost && (
<Link href={`/${nextPost.slug}`}>
next.config.js
Create a next.config.js
file in the root directory of your Next.js project if it doesn't exist already. Add the following code to the file:
module.exports = {
async rewrites() {
return [
{
source: '/:slug*',
destination: '/posts/:slug*',
},
];
},
};
After making these changes, the post URLs will be updated to the desired structure. For example, https://website-name.com/posts/test-post
will become https://website-name.com/test-post
.
Please note that you may need to restart your Next.js development server for the changes to take effect.