【问题标题】:How do I get URL rewrite to work in Laravel 5?如何让 URL 重写在 Laravel 5 中工作?
【发布时间】:2019-02-12 07:13:44
【问题描述】:

除了基本 URL 和 /site/public/ 文件夹中的文件之外,我无法让任何 Laravel 路由正常工作。

http://testurl/(通过 apache vhost 设置)工作,并加载主页。

http://testurl/blog) 不起作用(返回 404),但我想要它。

奇怪的是,http://testurl/index.php/blog 确实有效。

我在一百个不同的地方用 Google 搜索过,查看了无数 StackOverflow 问题,并尝试了所有能找到的方法,但没有任何效果。

我该如何解决这个问题?


配置信息

我在 Apache 2.4.29 上运行 Laravel 5.7,在 MacOSX 10.13.4 上运行 PHP 7.1.9。

我已经在httpd.conf 中启用了重写模块,如下所示:

LoadModule rewrite_module libexec/apache2/mod_rewrite.so
...
<Directory />
    AllowOverride all
    Require all denied
</Directory>

我的httpd-vhosts.conf 是这样设置的:

<VirtualHost *:80>
    DocumentRoot "/Library/WebServer/Documents/site/public"
    ServerName testurl
    <Directory /Library/WebServer/Documents/site/public>
            Order Allow,Deny
            Allow from all
    </Directory>
</VirtualHost>

/site/public/ 文件夹中的.htaccess 如下所示(我宁愿不必更改):

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

我的config/app.php 有以下行:

'url' => env('APP_URL', 'http://testurl'),

最后但同样重要的是,web.php 看起来像这样:

<?php

Route::get('/', function () {
    return view('home');
});
Route::get('blog', function () {
    return view('blog');
}); 

如果还有什么我遗漏的(或任何我可以尝试的),请告诉我。

最好是在部署到服务器时不需要我更改 Laravel 代码的解决方案。

感谢您的帮助!

【问题讨论】:

  • 请运行 sudo a2enmod rewrite 以交叉检查您是否启用了 mod_rewrite
  • @ChukwuemekaInya - 它确实在运行。

标签: php laravel macos apache mod-rewrite


【解决方案1】:

经过大量搜索,我找到了this question,它帮助我找到了答案。

我需要做的就是将AllowOverride All 添加到我的httpd-vhosts.conf 文件中,如下所示:

<VirtualHost *:80>
    DocumentRoot "/Library/WebServer/Documents/site/public"
    ServerName testurl
    <Directory /Library/WebServer/Documents/site/public>
            AllowOverride All
            Order Allow,Deny
            Allow from all
    </Directory>
</VirtualHost>

这解决了问题,现在一切都正常加载了。

【讨论】:

    猜你喜欢
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-15
    • 2017-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多