Francis Ngueukam
Francis Ngueukam

Reputation: 1024

Yii2 Trailing Slashes in URL is breaking the route

I configured UrlManager in a project and It was working the way I wanted. Now i tried to add a content whose name contains a trailing slash but i get an error 404 (Object not found).

For example: www.test.com/article/detail/id_of_article/title_of_article

title_of_article = People are ... => Work

title_of_article = 1/3 of People are ... => Doesn't Work (Object not Found)

The Trailing Slash is breaking the Url although it is encoded in %2F

This is how i create url:

Html::a(Html::encode($model->title), 
        ['article/detail', 'id' => $model->id, 'title' => $model->title])

I don't really know how I can deal with that.

Upvotes: 1

Views: 2296

Answers (3)

ScaisEdge
ScaisEdge

Reputation: 133400

Could be you need URL normalization

Since version 2.0.10 UrlManager can be configured to use UrlNormalizer for dealing with variations of the same URL, for example with and without a trailing slash.

NB by default UrlManager::$normalizer is disabled. You need to explicitly configure it in order to enable URL normalization.

see how here http://www.yiiframework.com/doc-2.0/guide-runtime-routing.html#url-normalization

Upvotes: 1

Yasin Patel
Yasin Patel

Reputation: 5731

For This , the best solution is to use slug names.

Instead of id and title, take one more field called slug_name in your database.

On Add or update of any record generate slug name and store in db.

For generating slug name, you can use custom function as below.

public function getSlugName($id,$title)
  {
    $slug=$id;
    if(isset($title) && $title!=null)
    {
      // remove all spacea
      $slug.='-'.str_replace(' ','-',strtolower($title)); 
    }
    $slug=preg_replace('/[^A-Za-z0-9\-]/', '', $slug); // Removes special chars.
    $slug=str_replace(array('--'), '-', $slug); // remove multiple --
    return $slug;
  }

This function will return you uniq name. So you can use it in url.

This is also help in SEO.

Upvotes: 1

Joji Thomas
Joji Thomas

Reputation: 46

There is an encodeParams property of UrlRule. Please try with that.

Upvotes: 0

Related Questions