Laravel总是返回404

时间:2015-05-19 09:12:25

标签: apache .htaccess mod-rewrite laravel

我使用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';
});

每个后端请求(http://domain.com/api*)都会从Laravel返回NotFoundHttpException in RouteCollection.php line 145(所以backend/public/index.php正在运行),例如:

http://domain.com/api
http://domain.com/api/test

感谢您的时间。

1 个答案:

答案 0 :(得分:1)

您需要将路线包裹在前缀为api的路线组中。例如:

Route::group(['prefix' => 'api'], function(){
    Route::get('/', function()
    {
        return 'Hello World';
    });

    Route::get('/test', function()
    {
        return 'Hello Test';
    });
});

原因是您的Laravel应用程序不在根域提供,而是在子文件夹中提供。因此,每个请求的URI将以api开头。

相关问题