如何解决在 Next.js 应用程序中生成动态 /robots.txt 文件
我需要一种动态响应 /robots.txt
请求的方法。
这就是为什么我决定选择getServerSideProps
https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering
如果从页面导出名为 getServerSideProps 的异步函数,Next.js 将使用 getServerSideProps 返回的数据在每个请求上预渲染此页面。
export async function getServerSideProps(context) {
return {
props: {},// will be passed to the page component as props
}
}
在 context
参数中,我们有 req
和 res
对象。
robots.txt
的响应将取决于 req.headers.host
值。
例如:
-
www.mydomain.com
应呈现生产robots.txt
文件 -
test.mydomain.com
应该呈现一个测试robots.txt
文件(我将在测试/暂存部署中使用该文件)。
这是我当前的代码:
pages/robots.txt.tsx
import React from "react";
import { GetServerSideProps } from "next";
interface Robots {
ENV: "TEST" | "PROD"
}
export const getServerSideProps : GetServerSideProps<Robots> = async (context) => {
const { req,res } = context;
const { host } = req.headers;
res.write("XXX");
res.end();
return({ // This is unnecessary (but Next.js requires it to be here)
props: {
ENV: "TEST"
}
});
};
const Robots: React.FC<Robots> = (props) => { // This is also unnecessary (but Next.js requires it to be here)
console.log("Rendering Robots...");
return(
<div>
I am Robots
</div>
);
};
export default Robots; // This is also unnecessary (but Next.js requires it to be here).
它似乎有效:
但奇怪的是,Next.js
要求我从该页面导出一个组件。并且还需要从 props: {}
返回一个 getServerSideProps
对象。
去这里的路是什么?我基本上使用 req,res
中的 getServerSideProps
来返回不是页面的内容。这是一种反模式吗?
更新
是的,这是一种反模式。您应该使用 rewrites
。查看所选答案。
解决方法
您可以将 API 路由用于逻辑,并在 Next.js 配置文件中将 /robots.txt
请求重写为 /api/robots
。
// next.config.js
module.exports =
// ...
async rewrites() {
return [
{
source: '/robots.txt',destination: '/api/robots'
}
];
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。