Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Changing posts path #155

Open
hayschan opened this issue May 16, 2023 · 1 comment
Open

Changing posts path #155

hayschan opened this issue May 16, 2023 · 1 comment

Comments

@hayschan
Copy link

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.

@hayschan
Copy link
Author

hayschan commented May 16, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant