Skip to content

Instantly share code, notes, and snippets.

@ahmedmusawir
Created October 30, 2018 05:08
Show Gist options
  • Save ahmedmusawir/b2bcd1478e46ed1557da1755a86b84da to your computer and use it in GitHub Desktop.
Save ahmedmusawir/b2bcd1478e46ed1557da1755a86b84da to your computer and use it in GitHub Desktop.
DEVOPS – REACT – Fixing the “cannot GET /URL” error on refresh with React Router
Catch-all
If you already have a server you’re using, this is probably your best bet. The main idea here is that you redirect all of your server requests to /index.html. The outcome is similar to Hash History. Any request that is made to your server will respond with the index page (and then fetch any JS resources you need), React Router will then take over and load the appropriate view. The actual code for this varies on which type of you have. Here are some examples
Express
--------------
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, 'path/to/your/index.html'), function(err) {
if (err) {
res.status(500).send(err)
}
})
})
Appache .htaccess
------------------
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
Nginx .conf
-----------
location / {
if (!-e $request_filename){
rewrite ^(.*)$ /index.html break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment