【问题标题】:Apache Rewrite rule with Laravel not workingLaravel 的 Apache 重写规则不起作用
【发布时间】:2015-07-20 05:22:53
【问题描述】:

我的目录结构如下:

/home/username/public_html
        my_laravel_app/
            .htaccess
            app/
            bootstrap/
            public/
                .htaccess
                index.php
                robots.txt
                ...etc (standard Laravel 4 public folder contents)
            vendor/
            ...etc (standard Laravel 4 files and folders)

我正在尝试使用 apache RewriteRule 将请求重定向到 http://example.com/~user/my_laravel_apphttp://example.com/~user/my_laravel_app/public/index.php。在第一个.htaccess文件中(my_laravel_app/目录下的那个,我有如下代码:

<IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteBase /~username/my_laravel_app
        RewriteCond %{THE_REQUEST} !public/
        RewriteRule ^(.*)$ public/index.php [R]
</IfModule>

当我将浏览器导航到http://example.com/~username/my_laravel_app 时,我正确地被重定向到http://example.com/~user/my_laravel_app/public/index.php,并且laravel 应用程序按预期加载,显示/ 的路由,如app/routes.php 中定义的那样。

但是,我希望重定向是内部的,也就是说,我不希望用户浏览器显示新位置。所以,我只是删除了规则上的[R] 标志。 .htaccess 文件现在包含:

<IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteBase /~username/my_laravel_app
        RewriteCond %{THE_REQUEST} !public/
        RewriteRule ^(.*)$ public/index.php
</IfModule>

现在,当我将浏览器定向到 http://example.com/~username/my_laravel_app 时,我得到一个 Laravel 糟糕的错误页面,说有一个 NotFoundHttpException。当我查看错误页面时,似乎重定向正在“工作”,因为我看到SCRIPT_NAME/~username/my_laravel_app/public/index.php

但是,我认为问题可能是 REQUEST_URI/~username/my_laravel_app/,而不是“/”,就像 Laravel 像正常一样安装在域的根目录中一样。所以看起来 Laravel 正在使用这个 REQUEST_URI 变量寻找路由匹配。

有没有办法让 Laravel 识别正确的路线?

【问题讨论】:

    标签: php apache .htaccess laravel mod-rewrite


    【解决方案1】:

    我在 Laravel 4.1 上遇到了同样的问题,并且似乎与我的 apache 配置有关,但是,我确实找到了一种解决方法,即将以下内容添加到 public/index.php 的顶部:

    $_SERVER['SCRIPT_NAME'] = 'path/to/laravel/index.php';

    // 注意:这是 mod_rewrite 和 laravel 的解决方法,它将 script_name 从 /path/to/laravel/public/index.php 更新为 /path/to/laravel/index.php。我完全忘记了它为什么起作用,但我认为当我追溯问题时,它与 symfony 依赖项中的某些东西有关。

    【讨论】:

    • 作为记录,我不喜欢这种解决方法,因为它是硬编码的,如果环境发生变化会失败。希望有人有更好的解决方案。
    • 我想将以下内容添加到 bootstrap/start.php 比上面的稍微好一点,但仍然不是很好: $_SERVER['SCRIPT_NAME'] = str_replace('/public', '', $_SERVER[ 'SCRIPT_NAME']);
    猜你喜欢
    • 2014-02-02
    • 1970-01-01
    • 2017-08-31
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-06
    相关资源
    最近更新 更多