'ReactJS app inside Laravel's public folder .htaccess configurations
I am hosting a React application inside the public directory of a Laravel app where:
/public_html/
app
bootstrap
config
database
public <--- React App Here
static <--- Belongs to React
index.html <--- Belongs to React
index.php <--- Belongs to Laravel
.htaccess <--- htaccess (2)
.htaccess <--- htaccess (1)
other laravel folders
.
.
.
The root directory's .htaccess
htaccess (1) contents are below, it's responsible for removing the /public
from the Laravel app's route:
RewriteEngine on
RewriteCond %{REQUEST_URI} !^public
RewriteRule ^(.*)$ public/$1 [L]
Laravel's public folder .htaccess
htaccess (2) contents are below, I never touched them:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Send Requests To Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
The problem is that when I access the app via https://myapp.com
React takes control over the routing, and redirects me to the https://myapp.com/home
view, while if I refresh the page, Laravel's route takes control and shows a Laravel 404 error that /home
route doesn't exist.
How can I fix .htaccess file to ignore React's routes and just load the index.html file while keeping Laravel's /api
routes working? Since all the React app routes are using Laravel's API controllers.
Solution 1:[1]
Add a RewriteCond for /api that redirects to php, the rest should go to the html file
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Send Requests To Front Controller...
RewriteCond %{REQUEST_URI} ^/api
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
RewriteCond %{REQUEST_URI} !^/api
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [L]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |