How to ensure unicity to url

You are viewing revision #1 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#2) »

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:

'post/<id:\d+>'=>'post/read',

This url will be valid:

post/read/id/5
post/read?id=5
post/5

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

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:

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
/**
 * 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.

13 0
16 followers
Viewed: 24 313 times
Version: Unknown (update)
Category: Tips
Tags: SEO, unique, URL
Written by: zaccaria
Last updated by: marcovtwout
Created on: Jul 26, 2011
Last updated: 12 years ago
Update Article

Revisions

View all history

Related Articles