netlify-templates / nextjs-blog-theme

A customizable Next.js and Tailwind blog starter. Designed by the Bejamas agency.

Home Page:https://bejamas-nextjs-blog.netlify.app

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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:

<Link
as={`/posts/${post.filePath.replace(/\.mdx?$/, '')}`}
href={`/posts/[slug]`}
>

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:

https://github.com/netlify-templates/nextjs-blog-theme/blob/b23a5838198383bc4d2c4b428f1995fd1e2dcc5d/pages/posts/%5Bslug%5D.js#L60C1-L61

https://github.com/netlify-templates/nextjs-blog-theme/blob/b23a5838198383bc4d2c4b428f1995fd1e2dcc5d/pages/posts/%5Bslug%5D.js#L73C25-L74

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.