我有一个 Next.js 应用程序,其中包含以下页面:
/
、/pre-registration
、/contest
、/profile
和 /auth
。我想在服务器上部署这个项目,但我希望我的用户只能访问 /pre-registration
页面,而不能访问其他页面。如果他们进入根域,他们应该被重定向到 /pre-registration
页面。
为此我需要做什么?我必须在项目中更改哪个文件?我可以在我的服务器上配置它吗?或者前端项目要改变?
我找到了答案。有几种方法可以解决这个问题。由于相对路径,添加 server.js (自定义服务器)会破坏页面的样式。所以,我找到了另一种方法。我更改了 next.config.js 文件如下:
// next.config.js
module.exports = {
async redirects() {
return [
{
source: '/',
destination: '/pre-registration',
permanent: true,
},
{
source: '/auth/login',
destination: '/pre-registration',
permanent: true,
},
{
source: '/auth/signup',
destination: '/pre-registration',
permanent: true,
},
{
source: '/profile',
destination: '/pre-registration',
permanent: true,
},
{
source: '/contest/:path*',
destination: '/pre-registration',
permanent: true,
},
];
},
};
如您所见,我单独重定向了每个路径并且它有效。最初,我使用了这段代码,但它给了我一个连接错误,并显示消息“重定向太多”:
/** @type {import('next').NextConfig} */
const nextConfig = {};
// next.config.js
module.exports = {
async rewrites() {
return [
{
source: '/:path*',
destination: '/pre-registration',
permanent: true,
},
];
},
};