sne25088
sne25088

Reputation: 127

Laravel always return 404

I use Laravel as backend (API REST) and AngularJS as frontend (consuming API). I would like to have redirects:

/api --> /backend/public (Laravel)
/    --> /frontend/app   (AngularJs)

Frontend runs without problem, but Laravel always return 404 for existing routes (NotFoundHttpException in RouteCollection.php).

Where I make a mistake?

My folder structure:

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

<VirtualHost *:80>
    ...
    DocumentRoot /var/www/
    <Directory />
        Options FollowSymLinks
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
    ...
</VirtualHost>

Part of backend/app/Http/routes.php

<?php

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

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

Every request to backend (http://domain.com/api*) return NotFoundHttpException in RouteCollection.php line 145 from Laravel (so backend/public/index.php is running), for example:

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

Thank you for your time.

Upvotes: 3

Views: 3968

Answers (1)

Hieu Le
Hieu Le

Reputation: 8415

You need wrap your routes inside a route group with a prefix of api. For example:

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

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

The reason is your Laravel application is not served at root domain but inside a child folder. Therefore, the URI of each request will start by api.

Upvotes: 1

Related Questions