Next.js 重定向
Next.js 重定向 指的是将进入的源请求更改为目标请求,并将用户重定向到该路径。当原始网络应用程序处于维护状态时,用户浏览或访问该网络应用程序时,我们希望将用户重定向到另一个网页或应用程序,仅限一定时间内。
创建项目设置: 按照以下步骤创建项目:
步骤1: 创建一个项目文件夹,并进入该目录。
mkdir foldername
cd foldername
步骤2: 在该文件夹中,通过终端使用以下命令创建项目:
npx create-next-app project
项目结构: 这个项目应该看起来像这样:
运行项目:
运行项目请使用以下命令:
npm run dev
注意: 默认情况下,它将在3000端口启动服务器。
语法: next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
}
module.exports = {
redirects: async () => {
return [
{
// Source Path ( from )
source: '/',
// Destination Path ( to )
destination: '/',
permanent: true,
},
]
},
}
redirects() 异步函数: 它预期接收一个包含源、目标和永久属性的对象数组:
参数:
- 源: 源是你想要重定向的路径。如果用户搜索该位置,他们将重定向到另一个位置。
- 目标: 目标是你想要重定向到的路径。用户搜索源位置时将到达的位置。
- 永久: 它接受一个布尔值。如果为真,搜索引擎将缓存重定向,否则不会缓存重定向。
示例 1: 从 /home 页面重定向用户到 /contact 页面:
在“页面”部分创建一个新的 JavaScript 文件 contact.js。当用户搜索 /home 时,用户应该到达显示 GeeksforGeeks 官方联系方式的 /contact 页面。
写入以下代码行到 contact.js 文件中以在发生重定向时显示:
// Contact Page Redirection
export default function Contact() {
return (
<div>
<h1 style={{ color: "green;" }}>GeeksforGeeks</h1>
<h3>Contact Details</h3>
<p>A-143, 9th Floor, Sovereign Corporate Tower, <br></br>
Sector- 136, Noida, Uttar Pradesh (201305) <br></br>
+91-7838223507 (Course related Queries)</p>
</div>
);
}
现在我们需要更新我们的next.config.js文件。将源更新为‘/home’,目标更新为‘/contact’。
以下更改是必要的:
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
}
module.exports = {
redirects: async () => {
return [
{
source: '/home', // source path /home
destination: '/contact', // destination path
permanent: true,
},
]
},
}
就是这样。如果用户搜索/home,用户将自动重定向到/contact页面。
示例2: 使用has对象并根据has对象中的类型、键和值来重定向用户。
语法: has对象使用以下语法来重定向特定的用户请求:
Valid `has` object shape is
{
"type": "header, cookie, query, host",
"key": "the key to check for",
"value": "undefined or a value string to match against"
}
我们将使用 类型:host 和 键:localhost。
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
}
module.exports = {
redirects: async () => {
return [
{
source: '/home',
has: [
{
type: 'host',
key: 'localhost',
value: '',
},
],
permanent: false,
destination: '/contact',
},
]
},
}
输出:
示例3: 当用户输入错误的路由并且重定向失败(404-页面未找到)时:
步骤1: 在页面目录中创建404.js文件。当重定向失败且用户到达404页面时,我们希望用户只重定向到/contact页面:
步骤2: 将以下代码插入 404.js 文件中:
// Importing the useEffect Hook.
import { useEffect } from "react"
// Importing the Router.
import { useRouter } from "next/router"
// Error function
export default function Error() {
// route object.
const router = useRouter()
// runs after every rendering.
useEffect(() => {
// Change the route /404 to /contact.
router.replace("/contact")
});
};
在上面的代码中,我们使用了Router和useEffect hook。每当重定向失败或用户到达404页面时,会自动重定向到/contact页面。
输出: