How to correctly set up 404 page, so that if user hits any route that does not exist, it redirects to this 404 page?
Currently I have this code:
import React from "react";
import Layout from "../components/layout";
import SEO from "../components/seo";
const NotFoundPage = () => (
<Layout>
<SEO title="404: Not found" />
<h1>NOT FOUND</h1>
<p>You just hit a route that doesn't exist... the sadness.</p>
</Layout>
);
export default NotFoundPage;
2
Answers
If the file is called
404.js
and you place it undersrc/pages/404.js
directory, it will make automatically the redirect for every non-existing page. According to their documentation:Keep in mind that under
develop
mode your404
, Gatsby overrides the default page and lists all your created pages and paths. However, you can still preview your404
page by clicking "Preview custom 404 page" to verify that it’s working as expected. This is useful when you’re developing so that you can see all the available pages.Under
build
mode everything works as expected.As Ferran Buireu wrote, the good explanation is on the GatsbyJS website:
https://www.gatsbyjs.com/docs/how-to/adding-common-features/add-404-page/
But sometimes this method doesn’t work when your site is running on Apache or Nginx webserver. You are getting the default Apache/Nginx 404 page instead of your beautiful GatsbyJS 404 page. That’s because your webserver… (surprise!) simply doesn’t find the page! And displays its own default 404 page.
How to display your own 404 page instead of default webserver 404 page? Just to add a special instruction to your virtual host config:
Apache:
ErrorDocument 404 /404/index.html
(link)Nginx:
error_page 404 /404/index.html;
(link)