【问题标题】:Is there a way in Laravel for all links/redirects to be with trailing slash?Laravel 中有没有办法让所有链接/重定向都带有斜杠?
【发布时间】:2017-04-29 15:11:33
【问题描述】:

我正在重新设计使用自定义代码构建的旧网站,现在我们使用 Laravel 框架(版本 5.3)。问题是旧网站的所有链接都带有斜杠。它具有出色的 SEO 和来自搜索引擎的许多访问,因此删除尾部斜杠不是选项。

在我的 routes/web.php 文件中,我有以下路线:

$router->get('texts/', 'TextController@index');
$router->get('texts/{slug}/', 'TextController@category');
$router->post('texts/search/', 'TextController@searchPost');
$router->get('texts/search/', 'TextController@search');

在带有斜杠的 html/blade 视图上显示链接不是问题,问题是重定向到路由链接。

App/Http/Controllers/TextController.php

public function searchPost()
{
    ...

    return $this->response->redirectToAction('TextController@search');
}

这会将我重定向到“texts/search”而不是“texts/search/”。是否有任何选项可以在 Laravel 中打开/关闭尾随斜杠或一些 hacky 方法来解决这个问题? .htaccess 重定向不是解决方案,因为它增加了一个重定向并减慢了网站速度。

【问题讨论】:

  • 您尝试命名路线了吗?试试看并使用此代码重定向 $this->response->redirect->route('route_name')
  • 是的,同样的问题,看起来 Laravel 在 redirectToAction() 和 redirectToRoute() 方法上使用了 rtrim('/')。有没有不修剪斜线的重定向方法?
  • 不,它不起作用:S 看起来我需要重写一些核心 Laravel 类,比如 Redirector...

标签: php laravel laravel-5


【解决方案1】:

我认为这可能很有用https://www.neontsunami.com/posts/redirect-trailing-slashes-in-laravel-5

只需根据需要进行调整,您可以删除 rtrim 函数调用并尝试 Redirect::to 方法。

【讨论】:

  • 这是作为答案发布的,但它不会尝试回答问题。它可能应该是编辑、评论、另一个问题或完全删除。
  • 没有足够的声誉来发表评论:)
  • 当您的代表 >= 50 时,您可以发布 cmets。在那之前,请耐心等待,系统设计成这样是有原因的。
  • 这实际上会有所帮助,我需要创建自己的 Redirector 类来覆盖 Laravel
【解决方案2】:

想通了,我需要扩展 UrlGenerator 类。

App/Library 文件夹中创建了 TrailingSlashUrlGenerator.php

namespace App\Library;

use Illuminate\Routing\UrlGenerator;

class TrailingSlashUrlGenerator extends UrlGenerator
{
    /**
     * Format the given URL segments into a single URL.
     *
     * @param  string  $root
     * @param  string  $path
     * @param  string  $tail
     * @return string
     */
    protected function trimUrl($root, $path, $tail = '')
    {
        return parent::trimUrl($root, $path, $tail).'/';
    }
}

App/Providers 文件夹中创建 RoutingServiceProvider:

public function register()
{
    $this->app['url'] = $this->app->share(function($app) {
        $routes = $app['router']->getRoutes();
        $app->instance('routes', $routes);

        $url = new TrailingSlashUrlGenerator(
            $routes, $app->rebinding('request', $this->requestRebinder())
        );

        $url->setSessionResolver(function ($app) {
            return $app['session'];
        });

        return $url;
    });
}

config/app.php中注册提供者:

App\Providers\RoutingServiceProvider::class,

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多