skip to Main Content

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&#39;t exist... the sadness.</p>
        </Layout>
    );
    
    export default NotFoundPage;

2

Answers


  1. If the file is called 404.js and you place it under src/pages/404.js directory, it will make automatically the redirect for every non-existing page. According to their documentation:

    To create a 404 page create a page whose path matches the regex
    ^/?404/?$ (/404/, /404, 404/ or 404). Most often you’ll want to
    create a React component page at src/pages/404.js.

    Keep in mind that under develop mode your 404, Gatsby overrides the default page and lists all your created pages and paths. However, you can still preview your 404 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.

    Login or Signup to reply.
  2. 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)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search