Gatsby Dynamic Routing 404 build

588 views Asked by At

I'm building a website with Gatsby and Strapi. I'm using dynamic routes.

With gatsby develop, everything fine.

With gatsby build, links between pages are working, but typing the URLs give me 404. Example: I can go from / to /room with a click but when I type /room, I get a 404.

How should I fix this? Am I missing something?

index.js routing part:

        <Router basepath="/">
          <Doors path="/" exitTransition={exitTransition}></Doors>
          <Room path="/room" exitTransition={exitTransition}></Room>
          <Sound path="/sound" sounds={sounds} currentSoundIndex={currentSoundIndex} setCurrentSoundIndex={setCurrentSoundIndex} audioPlayerRef={audioPlayerRef}></Sound>
          <Cloakroom path="/cloakroom" clothes={clothes}></Cloakroom>
          {clothesRoutes}
        </Router>

gatsby-node.js

exports.onCreatePage = ({ page, actions }) => {
  const { createPage } = actions
  if (page.path === `/`) {
    page.matchPath = `/*`
    createPage(page)
  }
}

Note: Local http-server build is working. But on my client's hosted server it's not. I'm using Router from @reach/router.

Thank you so much for your help!

2

There are 2 answers

0
Antbarras On BEST ANSWER

I got it resolved.

I simply needed to place an .htaccess file in the public directory with that content:

RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
0
Ferran Buireu On

Extending the solution proposed by @Antbarras. The .htaccess must not be placed in the public folder because it's an autogenerated directory that it's overridden in each build so if you place any file there, it will be lost in the next build because the source code doesn't have it.

The way of adding a permanent .htaccess in the public folder is through the static folder, which is a folder that its content it's cloned into the /public folder keeping the internal structure. So:

  • Create a /static folder at the root of the project
  • Add the .htaccess in the first level