.htaccess Laravel的公共文件夹中的ReactJS应用程序,htaccess配置

g6ll5ycj  于 2022-11-16  发布在  React
关注(0)|答案(2)|浏览(167)

我在Laravel应用的公共目录中托管了一个React应用,其中:

/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
             .
             .
             .

根目录的.htaccess htaccess(1)内容如下所示,它负责从Laravel应用的路由中删除/public

RewriteEngine on
RewriteCond %{REQUEST_URI} !^public
RewriteRule ^(.*)$ public/$1 [L]

Laravel的公共文件夹.htaccess htaccess(2)的内容如下,我从来没有碰过它们:

<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]

问题是,当我通过https://myapp.com React访问应用程序时,React会控制路由,并将我重定向到https://myapp.com/home视图,而如果我刷新页面,Laravel的路由会控制并显示一个Laravel 404错误,即/home路由不存在。
我如何修复.htaccess文件以忽略React的路由并只加载index.html文件,同时保持Laravel的/api路由工作?因为所有React应用路由都使用Laravel的API控制器。

htrmnn0y

htrmnn0y1#

为重定向到php的/api添加RewriteCond,其余内容应转到html文件

<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]
kmpatx3s

kmpatx3s2#

我可以给予你我的例子,我最近也陷入了同样的问题,试试这个,如果它对你有帮助的话...
我有一个名为server的文件夹,然后在server中,我在laravel中有我的后端API,react部分在托管的public_html文件夹中。
以下配置适合我

RewriteCond %{HTTPS} !on 
RewriteCond %{HTTP_HOST} =YourDomainHere
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L,NE]

Options -MultiViews

RewriteEngine on

# Final rule for back end index
RewriteRule ^server/public/index\.php$ - [L]
# Redirect to back end index
RewriteRule ^api$ server/public/index.php [L]
RewriteRule ^api/.* server/public/index.php [L]

# the below code will help you while you are addressing your react's index.html

  RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.html [QSA,L]

相关问题