C
C
Crash2017-05-08 12:28:35
Yii
Crash, 2017-05-08 12:28:35

What is the most elegant way to solve the trailing slash problem in Yii2?

The problem is not new, but so far I have not found a clear solution.
Let's say there are 2 url options:

site.com/index
site.com/index/

By default, the first one will work fine, and the second one will return a 404 error.
If you add an additional option to the urlManager:
'suffix' => '/',
Then everything will work exactly the opposite. There can be many url parsing rules, and for each of them, providing an optional slash is not an option, I think.
What is the optimal solution for this case?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav, 2017-05-08
@Bandicoot

https://github.com/yiisoft/yii2/issues/7670

$config = [
    // ...
    'params' => require(__DIR__ . '/params.php'),

    // redirect to the page with the trailing slash
    'on beforeRequest' => function () {
        $app = Yii::$app;
        $pathInfo = $app->request->pathInfo;
        if (!empty($pathInfo) && substr($pathInfo, -1) !== '/') {
            $app->response->redirect('/' . rtrim($pathInfo) . '/', 301);
        }
    },
];

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question