Search code examples
.htaccessreactjsreact-router-v4

Refresh page on apache with React doesn't work


I'm trying to use React to create a SPA, but I'm running into problem when trying to reload the page.

Before I continue, I must say I already read these questions this and this. I manageg to made it work, but only for the first url.

For example, I have a blog page containing all the posts, accessed via this url mysite.com/blog. This one works fine, if I refresh the page, everything reloads again.

However, when I try to access a single post using a dynamic url, then the page doesn't work. For example, I have this router setup:

// Definiton
<Route path="/post/:url" component={Post} />

// Link
<NavLink to={"post/" + post.url}>...</NavLink>

// Url on the browser
mysite.com/post/this-is-my-first-post

In this case, it's not working. This is my .htaccess file:

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteBase /
    RewriteRule ^index.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L]
</IfModule>

After looking more at the problem, I noticed it's trying to load the main files from a different location. For example, when I'm on the page mysite.com/blog it's loading the .css and .js files from mysite.com.

But when I'm the page mysite.com/post/this-is-my-first-post and I refresh the page, it's trying to load the .css and .js files from the directory mysite.com/blog.

I did what Stuffix told in the answe, to check the url definition and also the config at my apache, but everything is enabled and working, just like the answer says.


Solution

  • Well, after looking at some other projects I have using Angular, I noticed one thing, and it was easier than I tought.

    Just had to add the tag base on the head of my index.html.

    <base href="/" />