0

I'm redesigning old website which is built with custom code, and now we are using Laravel framework (version 5.3). The problem is that old website has all links with trailing slashes. It has great SEO and many visits from search engines so removing trailing slashes is not the option.

In my routes/web.php file i have following routes:

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

Showing links on html/blade views with trailing slashes is not the problem, problem is redirecting to route links.

App/Http/Controllers/TextController.php

public function searchPost()
{
    ...

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

This redirect me to "texts/search" instead on "texts/search/". Is there any options to turn on/off trailing slashes in Laravel or some hacky way to fix this ? .htaccess redirect is not the solution because it adds one more redirect and slows down website.

fsasvari
  • 1,891
  • 19
  • 27
  • Did you try to name the routes? Try it and use this code to redirect $this->response->redirect->route('route_name') – Giacomo M Dec 14 '16 at 10:22
  • Yes, same problem, looks like Laravel is using rtrim('/') on redirectToAction() and redirectToRoute() methods. Is there any redirect method that's not triming slashes ? – fsasvari Dec 14 '16 at 10:25
  • Try this http://stackoverflow.com/questions/24728417/laravel-add-trailing-slash-with-redirectroute#28264195 – Zakaria Acharki Dec 14 '16 at 10:30
  • Nah, it doesn't work :S Looks like I will need to override some core Laravel classes like Redirector... – fsasvari Dec 14 '16 at 10:39

1 Answers1

0

Figured it out, I needed to extend UrlGenerator class.

Created TrailingSlashUrlGenerator.php inside App/Library folder:

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).'/';
    }
}

Create RoutingServiceProvider in App/Providers folder:

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;
    });
}

Register provider in config/app.php:

App\Providers\RoutingServiceProvider::class,
fsasvari
  • 1,891
  • 19
  • 27