Search code examples
reactjsreact-router-dom

React - Links not updating to new base url after deploying webpage


So, still learning React, and getting there. I've deployed my react webpage to my online testserver, and it is communicating with my Strapi backend on Heroku. Now, all my links set with <Link to=> won't update to the new path, so they are all still pointing to the root, just like with the localhost:3000 setup.

Here's why I have tried so far:

  1. I have changed the base in my main html file to <base href="/directoryname/">
  2. I have changed the Route to like this setup: <Route path="/directoryname/contact" element={<Contact/>} />
  3. I have changed the "homepage" parameter in package.json to "homepage": "http://www.example.com/directoryname",

I can't figure out why my links are still pointing to "/"? What did I forget?

EDIT: For others with the same problem: The below post fixed one part of it, using <BrowserRouter basename="/directoryname">, and setting base href back to "/". When this got correct, however, all pages except the home went 404 when trying to access directly from URL. I was missing a .htaccess file redirecting * to the html file, and I solved that part by adding a .htaccess in the project root, like this.

RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . /directoryname/index.html [L]

Solution

  • Set the basename on BrowserRouter, then keep your <Routes> without the basename (react router will automatically prepend it to both the routes and the links).

    Leave the <base> HTML tag in as you have it.