adelowo ajibola
adelowo ajibola

Reputation: 41

React Router not functional when deployed in a sub-directory On Apache

I'm having quite an issue deploying my react app to a sub-directory on appache. I am using create-react-app and React router v4. When i visit the Url www.example.com/myApp. the html i am rendering as my homepage gets rendered properly.

But if i try to visit the register page by typing the route manually in the address bar, i get a 404 Not found error.

What i have done.

  1. I have set the basname of my BrowserRouter to the subdirectory.
  2. I have also set the homepage property in package.json.
  3. I have created .htaccess file.

Please i have been at this for days trying to figure out what i am doing wrong but i can not seem to figure it out.

Upvotes: 4

Views: 634

Answers (2)

batucha
batucha

Reputation: 1

When you have structure like you said

/ mysite.com
 ├─ app
 │ ├─ index.html
 │ └ ...
 └ .htaccess

You need to make sure that all your requests asking for documents (text/html) sent to mysite.com/app and any subsequent segments, are being redirected to mysite.com/app/index.html. To set up this configuration, you need to add some RewriteCond in your .htaccess.

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /

  # Browsers will specifically ask for HTML (among other things) on initial page load
  # That is, if the *user* tries to access a *nonexisting* URL, the app is loaded instead
  # but if a webpage attempts to load a missing resource it will return 404.

  # if (HTTP_ACCESS.contains('text/html') && file_not_exists(REQUEST_FILENAME))
  RewriteCond %{HTTP_ACCEPT} text/html
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_URI} app [NC]
    RewriteRule ^app/.*$ /app/index.html [E]

  # If you have a fallback document under mysite.com directory.
  RewriteRule ^ - [L]
</IfModule>

Special thanks to VLRoyrenn for the explanation, you can find the answer here.

Upvotes: 0

dcchuck
dcchuck

Reputation: 344

Apache attempts to find a resource for the requested route. You need to redirect all requests to your index so the react bundle can be loaded and react-router can do its thing

This has been addressed a few times so I'll reference other helpul answers

Change the VirtualHost configuration (typically found in /etc/httpd/conf.d\vhosts.conf) by adding the following Rewrite* lines:

<VirtualHost *:8080>
  ServerName example.com
  DocumentRoot /var/www/httpd/example.com

  <Directory "/var/www/httpd/example.com">
    ...

    RewriteEngine on
    # Don't rewrite files or directories
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^ - [L]
    # Rewrite everything else to index.html to allow html5 state links
    RewriteRule ^ index.html [L]
  </Directory>
</VirtualHost>

SOURCE

Upvotes: 0

Related Questions