apache - Laravel 总是返回 404

标签 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';
});

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/

相关文章:

apache - 如何将此 apache 重写转换为 nginx?

.htaccess - mod_rewrite 删除 .php 扩展名并保留 GET 参数

java - Apache POI : How to set font style for a field (PAGE, PAGENUM, PAGEREF...)

apache - 从 1&1 到 AWS EC2 实例的 SSL 证书不起作用

c++ - Apache 模块共享内存对象

apache - 面向 SaaS 产品客户的自定义域功能

php - 使用 dockerfile 在 docker 中安装 mongodb 驱动程序

php - 如何将特定目录中的所有重写 x.php 转换为 x.css?

css - 有人知道如何通过 apache RewriteRule 将 "opera9fixes.css"仅提供给 opera 9 吗?

apache - 为 SEO 和漂亮的 URL 重写 map