【问题标题】:How to display custom 410 page with nextJs如何使用 nextJs 显示自定义 410 页面
【发布时间】:2021-09-12 12:00:50
【问题描述】:

我正在尝试在我的 nextjs 应用上处理 410 代码。我已经设置了一个 404 页面,因为它很容易由 nextjs 管理。但我不知道如何显示自定义 410 页面。 我试图浏览_error 页面并检查httpStatusCode,但它似乎只能处理5xx 错误。

有没有办法显示自定义 410 页面? 而且,我应该尝试显示 410 页面还是只让浏览器显示错误(我不确定这里的最佳做法是什么)?我刚刚在我的网站上进行了“大”迁移,并且有几个 410(不取决于我)。

如果需要,我可以提供更多信息 谢谢

【问题讨论】:

    标签: node.js next.js seo http-status-code-410


    【解决方案1】:

    你可以做这样的事情。检查一个不存在的页面是否应该用 404 或 410 响应的逻辑可以根据您的需要进行修改。

    // _error.js
    
    import Error from 'next/error';
    
    const CustomError = ({ statusCode }) => (
      <Error
        statusCode={statusCode}
        title={
          statusCode === 410
            ? 'The requested resource is no longer available'
            : undefined
        }
      />
    );
    
    const gonePages = ['gone', 'moved', 'foo/bar'];
    
    const compareURLs = (n, h) => {
      const nParts = n.split('/').filter(Boolean);
      const hParts = h.split('/').filter(Boolean);
      return (
        nParts.length <= hParts.length &&
        nParts.every((part, i) => part === hParts[i])
      );
    };
    
    const getServerSideProps = async ({ req, res }) => ({
      props: {
        statusCode:
          res.statusCode === 404 &&
          gonePages.some((slug) => compareURLs(slug, req.url))
            ? 410
            : res.statusCode,
      },
    });
    
    export default CustomError;
    export { getServerSideProps };
    

    检查沙盒:codesandbox.io/s/zealous-driscoll-ru62j

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 2019-09-14
      • 2013-06-16
      • 1970-01-01
      相关资源
      最近更新 更多