我使用 Laravel 作为后端(API REST),使用 AngularJS 作为前端(使用 API)。 我想要重定向:
/api --> /backend/public (Laravel)
/ --> /frontend/app (AngularJs)
前端运行没有问题,但 Laravel 总是为现有路由返回 404(RouteCollection.php 中的 NotFoundHttpException)。
我哪里做错了?
我的文件夹结构:
/var/www
-- .htaccess (1)
-- frontend
---- app
------ index.html
------ .htaccess (2)
-- backend
---- public
------ index.php
------ .htaccess (3)
.htaccess (1)
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Backend
RewriteRule ^api(.*) backend/public/$1 [L]
# Frontend
RewriteRule ^(.*) frontend/app/$1 [L]
</IfModule>
.htaccess (2)
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [L]
</IfModule>
.htaccess (3)
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
RewriteBase /api/
# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
Apache 配置
<VirtualHost *:80>
...
DocumentRoot /var/www/
<Directory />
Options FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
</Directory>
...
</VirtualHost>
部分backend/app/Http/routes.php
<?php
Route::get('/', function()
{
return 'Hello World';
});
Route::get('/test', function()
{
return 'Hello Test';
});
Laravel 对后端 (http://domain.com/api*
) 的每个请求都返回 NotFoundHttpException in RouteCollection.php line 145
(所以 backend/public/index.php
正在运行),例如:
http://domain.com/api
http://domain.com/api/test
感谢您的宝贵时间。
最佳答案
您需要将您的路由包装在前缀为 api
的路由组中。例如:
Route::group(['prefix' => 'api'], function(){
Route::get('/', function()
{
return 'Hello World';
});
Route::get('/test', function()
{
return 'Hello Test';
});
});
原因是您的 Laravel 应用程序不是在根域中提供的,而是在子文件夹中提供的。因此,每个请求的 URI 都将以 api
开头。
关于apache - Laravel 总是返回 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30321343/