Ask Your Question
3

How can I display the identical page for two different URLs using Next Js?

asked 2021-11-01 11:00:00 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-04-07 02:00:00 +0000

ladyg gravatar image

There are multiple ways to display the identical page for two different URLs using Next.js:

  1. Use next.config.js to add rewrite rules:

You can use the rewrites property to add URL rewrite rules in your next.config.js file. For example, if you want to display the same page for /about and /about-us, you can add the following code:

module.exports = {
  async rewrites() {
    return [
      { source: '/about-us', destination: '/about' },
    ]
  },
}
  1. Use dynamic routing:

You can use dynamic routing to match multiple URLs to the same page. For example, if you want to display the same page for /post/1 and /article/1, you can create a dynamic page at /pages/post/[slug].js and use the slug parameter in the page to load the corresponding data. Here's an example:

import { useRouter } from 'next/router'

function Post() {
  const router = useRouter()
  const { slug } = router.query

  // Load data for the post with `slug`
  // ...

  return (
    // Render the post
  )
}

export default Post
  1. Use URL aliases:

You can use URL aliases to create a shorter or more readable version of a URL. For example, if you want to make /products alias to /shop, you can add the following code to your next.config.js file:

module.exports = {
  async redirects() {
    return [
      { source: '/shop', destination: '/products', permanent: true },
    ]
  },
}

Once you've set up the URL aliases, you can use the /shop URL or the /products URL to display the same page.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-11-01 11:00:00 +0000

Seen: 10 times

Last updated: Apr 07 '23