我使用代码来分隔我网站中的 HTTPS 和 HTTP 页面
问题是:当我在 HTTP 上时,指向 HTTPS 的链接没有 WWW,反之亦然。我没有在脚本中发现问题。
public function createUrl($route, $params = array(), $ampersand = '&')
{
$url = parent::createUrl($route, $params, $ampersand);
// If already an absolute URL, return it directly
if (strpos($url, 'http') === 0) {
return $url;
}
// Check if the current protocol matches the expected protocol of the route
// If not, prefix the generated URL with the correct host info.
$secureRoute = $this->isSecureRoute($route);
if (Yii::app()->request->isSecureConnection) {
return $secureRoute ? $url : 'http://' . Yii::app()->request->serverName . $url;
} else {
return $secureRoute ? 'https://' . Yii::app()->request->serverName . $url : $url;
}
}
public function parseUrl($request)
{
$route = parent::parseUrl($request);
// Perform a 301 redirection if the current protocol
// does not match the expected protocol
$secureRoute = $this->isSecureRoute($route);
$sslRequest = $request->isSecureConnection;
if ($secureRoute !== $sslRequest) {
$hostInfo = $secureRoute ? 'https://' . Yii::app()->request->serverName : 'http://' . Yii::app()->request->serverName;
if ((strpos($hostInfo, 'https') === 0) xor $sslRequest) {
$request->redirect($hostInfo . $request->url, true, 301);
}
}
return $route;
}
private $_secureMap;
/**
* @param string the URL route to be checked
* @return boolean if the give route should be serviced in SSL mode
*/
protected function isSecureRoute($route)
{
if ($this->_secureMap === null) {
foreach ($this->secureRoutes as $r) {
$this->_secureMap[strtolower($r)] = true;
}
}
$route = strtolower($route);
if (isset($this->_secureMap[$route])) {
return true;
} else {
return ($pos = strpos($route, '/')) !== false
&& isset($this->_secureMap[substr($route, 0, $pos)]);
}
}
}
代码改编自:http ://www.yiiframework.com/wiki/407/url-management-for-websites-with-secure-and-nonsecure-pages/