简体   繁体   中英

View article title on url instead of id in yii 1 web application for SEO pretty urls

i have articles in my yii web application, i want to view article title instead of id at the url, i have followed this link: http://www.yiiframework.com/forum/index.php/topic/43874-urlmanager-show-title-instead-of-id/ i changed createUrl function to be :

Yii::app()->createUrl('home/article',array('id'=>$article->id,'title' => $article->title); 

and add the following rules to url manager as below :

        '<action:\w+>'=>'home/<action>',
            '<action:\w+>/<id:\d+>'=>'home/<action>',
             '<controller:\w+>/<id:\d+>'=>'<controller>/view',
            '<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
            '<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
              'article/<id>/<title>'=>'home/article/view/'

article url now like : http://localhost/test/article?id=6 i want to be
http://localhost/test/article/article-title

thank you in advance .

I do something similar, but you don't want to avoid using a unique Id to find your article, because you can't depend on titles being unique or even not ever changing.
It's good practice to not use an autonumeric Id at least publicly in the URL, so you could something like this:
"article/<key:\\w{6}>/<title>"

So, the URLs will be like: article/e87qy2/The_book_title_here And you just ignore the title and use the key that must be unique for every article.
Of course, an alphanumeric hash or key is not very diferent than a numeric Id, but at least you got rid of revealing interal information about your Database by showing that you have autonumeric primary keys.

If you really really unavoidably want to have just the title in the url, well, first make sure any newly created article is unique, and then just use it as a unique key to find the article.
Avoiding two equal articles may require that you add numbers 2, 3, etc. at the end to make them different.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM