How can I block file system routing for only one page in nextjs?
In spite of using Custom server, I can not apply useFileSystemPublicRoutes : false
option because some pages is still accessed through file system router.
is there another way? or is it best to me to register every page on custom server and use useFileSystemPublicRoutes : false
option?
Thanks in advance.
You can either use rewrites
or redirects
in next.config.js (Next v10.1 or above), you won't need a custom server.
You don't need to disable the useFileSystemPublicRoutes
option, because as you said some pages should still be accessed.
let's say you have the below page folder structure:
pages
├── file_accessible.tsx
├── file_should_be_disabled.tsx
├── file_accessible_by_different_route.tsx
Assuming you have a 404 page, here is an example of using redirects
module.exports = {
async redirects() {
return [
{
source: '/file_should_be_disabled', // this path will be redirected to 404
destination: '/404',
permanent: true,
},
{
source: '/abc',
destination: '/file_accessible_by_different_route', // when visiting /abc, you will be redirected to this path
},
]
},
}
Both rewrites
and redirects
and solve you problem, in case you also want to know the difference between rewrites
and redirects
:
Rewrites act as a URL proxy and mask the destination path, making it appear the user hasn't changed their location on the site. In contrast, redirects will reroute to a new page and show the URL changes.
ref:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With