Schnecke
Schnecke

Reputation: 582

React Router Gives 404 error on production

React Router works on local machine, Chrome but not on safari and other browsers,

 <Switch>
    <Route exact path={"/"} component={Home} />
    <Route path="/programs/:slug" component={Programs} />
    <Route path="/page/:slug" component={Page} />
    <Route component={NotFound} />
</Switch>

thats my code but it works perfectly in development mode no errors but on production, safari gives 404 error when i navigate to programs/:slug or page/:slug

Upvotes: 6

Views: 6502

Answers (5)

zohaib aslam
zohaib aslam

Reputation: 1

This is occurring because your site is a react based SPA (Single Page Application).

When you visit the site via the root / it is automatically loading the index.html which is your application, and then when you visit other pages you never actually leave the index.html page

So it loads in additional data and simulates a browser page change.

However when you make a fresh request for example by going to one of those sub pages directly or hitting refresh while on them the web server is being requested to serve that file… but the file doesn’t actually exist… hence the 404 error.

The way around this is via redirects, you’ll want to have a _redirects file in your deploy folder that contains

When you run the command to build the project.

npm run build

then simply create a new file _redirect and paste this line

/* /index.html 200

then redeploy the project and it will work fine.

Upvotes: 0

Ericksan Pimentel
Ericksan Pimentel

Reputation: 168

I added this to ./public_html/.htaccess file

<IfModule mod_rewrite.c>

  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-l
  RewriteRule . /index.html [L]

</IfModule>

found the solution at: How to fix "404" error when directly accessing a component in react

Upvotes: 0

GarryOne
GarryOne

Reputation: 1488

If you're using pm2 serve, you can simply add the --spa flag.

Upvotes: 1

Schnecke
Schnecke

Reputation: 582

I added this to .htaccess

RewriteBase /
RewriteCond %{REQUEST_URI} !^/(assets/?|$)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]

Thanks to Kishan Mundha explanation

Upvotes: 9

Kishan Mundha
Kishan Mundha

Reputation: 3141

You may need to configure single entry point index.html on server. All url should target to index.html and entry point will decide how to render and content based on route.

Upvotes: 2

Related Questions