There are multiple ways to display the identical page for two different URLs using Next.js:
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' },
]
},
}
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
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.
Asked: 2021-11-01 11:00:00 +0000
Seen: 10 times
Last updated: Apr 07 '23