Difference between #2 and #1 of How to ensure unicity to url

unchanged
Title
How to ensure unicity to url
unchanged
Category
Tips
unchanged
Tags
SEO, unique, URL
changed
Content
Ensure uniciy to url
------------------

Many time for SEO porpouses is important that each page will have a unique
address.

If, for example, we have a rule like:

~~~
[php]
  'post/<id:\d+>'=>'post/read',
~~~

This url will be valid:

~~~
[php]
post/read/id/5
post/read?id=5
post/5
~~~


If we have a suffix, for example .html, also this url will be available:

~~~
[php]
post/read/id/5.html
post/read.html?id=5
post/5.html
~~~

A total of 6 url, that is not seo compliant.

The solution is quite simple, just write this in your controller:



~~~
[php]
	public function beforeAction($action)
	{
		
		if (Yii::app()->request->url !=
CHtml::normalizeUrl(array_merge(array($this->route), $_GET)))
			$this->redirect(CHtml::normalizeUrl(array_merge(array($this->route),
$_GET)), true, 301);
		
		return parent::beforeAction($action);
	}
~~~

This will redirect all alternative url to the one 'legal'. Using 301 instead 302
will make the browser (and, we hope, google bots) aware that the correct address
is another one.

You can implement a master class for semplicity:



~~~
[php]
<?php
/**
 * BlockController is a customized base controller class.
 * All controller classes with unique url  should extend from this base class.
 */
class BlockController extends Controller
{
	public function beforeAction($action)
	{
		
		if (Yii::app()->request->url !=
CHtml::normalizeUrl(array_merge(array($this->route), $_GET)))
			$this->redirect(CHtml::normalizeUrl(array_merge(array($this->route),
$_GET)), true, 301);
		
		return parent::beforeAction($action);
	}

}
~~~

Notice that you cannot add this rule for actionError and actionIndex, so if you
want to make unique addresses in the site controller you cannot extend the
master controller, but you have to implement a special method with exception for
this two actions.

Links
-----
- [Chinese version](http://www.itkuaixun.com/bbs/thread-50-1-3.html
"Chinese version")