简体   繁体   English

如何在 Next.js 中为 404 页设置状态代码 404 而不是 200

[英]How to set status code 404 instead of 200 for 404-page in Next.js

I have inquired about the way of setting 404 status code to 404-page in Next.js but the response I was given was that this is not true, that the status code is 404 by default.我询问了在 Next.js 中将 404 状态码设置为 404-page 的方法,但得到的答复是这不是真的,状态码默认为 404。 I was not able to present print screens in the comment, so I want to present them here, and possibly get the answer I am after.我无法在评论中展示打印屏幕,所以我想在这里展示它们,并可能得到我想要的答案。 Truth is that all the bad requests have status code of 404, but the 404-page itself has status 200事实是,所有错误请求的状态代码都是 404,但 404 页面本身的状态代码是 200 在此处输入图片说明 as you can see, the first two positions are with status code 200. I want to trigger 404 every time the url does not match a page in my pages directory, but to be returned with status code 404 instead of 200. Or if this is possible I would prefer to have it redirected with status code 301 to page 404, and the url after redirect to be eg.如您所见,前两个位置的状态代码为 200。每次 url 与我的页面目录中的页面不匹配时,我想触发 404,但返回状态代码为 404 而不是 200。或者如果这是可能我更愿意将状态代码 301 重定向到第 404 页,重定向后的 url 为例如。 /404?url=%2Fbadrequest. /404?url=%2Fbadrequest。 Would you please at least point me in the direction.请你至少指出我的方向。 I don't know whether it should be done client or server side.我不知道应该在客户端还是服务器端完成。 I imagine I need to react server side to set the proper response code, but how?我想我需要对服务器端做出反应来设置正确的响应代码,但是如何呢? And to redirect and build up an url like /404?url=%2Fbadrequest does it have to be done client or server side?并重定向和建立一个像 /404?url=%2Fbadrequest 这样的 url 是否必须在客户端或服务器端完成?

Many thanks非常感谢

The first two requests you are referring to are script and fetch/XHR requests not the page (see Type , it will be document for pages; alternatively you can select "Doc" in filters).您所指的前两个请求是 script 和 fetch/XHR 请求,而不是页面(请参阅Type ,它将是页面的document ;或者您可以在过滤器中选择“Doc”)。 The page ( /badrequest ) is requested in the last request in your image (and responded with 404 status code).该页面 ( /badrequest ) 在您图像的最后一个请求中被请求(并以404状态代码响应)。 Those JS files are just used to render the 404 error component.那些 JS 文件只是用来渲染404错误组件。

For the redirect part you can do something like this:对于重定向部分,您可以执行以下操作:

// pages/[...slug.js]

const Fake = () => <></>;
export default Fake;

const getServerSideProps = async ({ req }) => {
  return {
    redirect: {
      destination: `/404?url=${encodeURI(req.url)}`,
      permanent: true
    }
  };
};

export { getServerSideProps };
// pages/404.js

import { useRouter } from "next/router";
import { useEffect, useState } from "react";

const ErrorPage = () => {
  const { asPath: path } = useRouter();
  const [currentPath, setCurrentPath] = useState("");

  useEffect(() => {
    setCurrentPath(
      decodeURI(
        new URLSearchParams(path.replace(/^.*?\?/, "")).get("url") || ""
      )
    );
  }, [path]);

  return <div>{currentPath} Not Found</div>;
};

export default ErrorPage;

Result:结果:

Code Sandbox: codesandbox.io/s/bitter-glade-btrcp代码沙盒: codesandbox.io/s/bitter-glade-btrcp


PS: Status code 308 means "Permanent Redirect" PS:状态码308表示“永久重定向”

If you want 301 status code, then change pages/[...slug.js] to this:如果您想要301状态代码, pages/[...slug.js]更改为:

const Fake = () => <></>;
export default Fake;

const getServerSideProps = async ({ req, res }) => {
  res.writeHead(301, { location: `/404?url=${encodeURI(req.url)}` }).end();
  return { props: {} };
};

export { getServerSideProps };

I've updated the sandbox accordingly.我已经相应地更新了沙箱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM