Redirect using 301 instead of 302

Hello,

Will it be possible to specify the redirect code type to the redirect function?

Some times it's important to do a 301 redirect due to SEO, to avoid duplicate contents.

Thank you :)

The redirect function (in CHttpRequest) simply issues a Location header. What would you suggest to do to specify a status code here?

I suggest to make the redirect function look like this:



public function redirect($url,$terminate=true, $status_code = 302)


{


	if(strpos($url,'/')===0)


		$url=$this->getHostInfo().$url;


	if($status_code == 301)


		header("HTTP/1.1 301 Moved Permanently");


	header('Location: '.$url);


	if($terminate)


		Yii::app()->end();


}


And, in this case, the CController redirect function should look like this



public function redirect($url,$terminate=true, $status_code = 302)


{


	if(is_array($url))


	{


		$route=isset($url[0]) ? $url[0] : '';


		$url=$this->createUrl($route,array_splice($url,1));


	}


	Yii::app()->getRequest()->redirect($url,$terminate, $status_code);


}


What do you think about this little improvement?

Thanks :)

Thanks! Will add this.

Hi Qiang,

You added the parameter to the redirect funcion in CController and CHttpRequest, but the if clause has not beed added, in the CHttpRequest and the CController function receives the parameter but it doesn't send it to the CHttpRequest function.

It's in the header() call (the last parameter).

Oh sorry, it's true.

But the CController redirect function is not sending the statusCode parameter to the CHttpRequest function.

ah, yes, thanks!

Wouldn't it make sense to move redirect or sendFile to a separate CHttpResponse object. Output (also non-header) elsewhere should also be moved to such a Response object. The sending of the response will be done at the end of the application lifetime and therefore you would be able to change stuff all the way (and do functional testing on the response including headers).

Having a response object handle sending headers, redirects is more logical I think.

Also see Zend Framework’s response object

Yes, it makes sense to have CHttpResponse object (like we used to have in Prado, and also in ZF). The initial decision of removing CHttpResponse was mainly for simplicity.