我目前正在更新一个现有的实时网站,以使用漂亮的URL。我已经让网址工作,但我的问题是,在我启用漂亮的网址后,所有来自谷歌等网站的旧链接都将停止工作。他们只是重定向到首页。示例;旧网址:http://www.dreambulgarianproperties.com/index.php?r=properties%2Fproperty%2Fview&id=37重定向到首页
新网址:http://www.dreambulgarianproperties.com/properties/property/view?id=37正如从两个url中应该看到的那样。
我的.htaccess文件是这样的:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1
我的UrlManager配置是这样的;
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => false,
'rules' => [
'<action:'w+>' => 'site/<action>'
],
],
这个网站运行良好,我只是担心如果我更改网址会失去谷歌流量。
有没有一种方法可以告诉Yii继续解析旧的URL,同时显示和处理新的、漂亮的URL?
我发现这样做很巧妙。我扩展了UrlManager,并像这样更新了parseRequest()方法;
public function parseRequest($request) {
$url = Yii::$app->request->url;
if ($pos = strpos($url, 'index.php?r=') == false) {
return parent::parseRequest($request);
}
Yii::trace('Pretty URL not enabled. Using default URL parsing logic.', __METHOD__);
$route = $request->getQueryParam($this->routeParam, '');
if (is_array($route)) {
$route = '';
}
return [(string) $route, []];
}
现在,如果有像index.php这样的查询字符串?r=控制器/操作它将处理它,否则它将控制权交回父级UrlManager进行正常处理。
为了让我的seo保持最新,我在每个页面的标题中添加了一个规范的链接,这样谷歌就知道使用漂亮的url进行索引。
在/vvendor/yiisoft/yii2/web/urlManager.php内将parseRequest方法替换为:
public function parseRequest($request)
{
$enable = true;
$url = Yii::$app->request->url;
if ($pos = strpos($url, 'index.php?r=') == true) {
$enable = false;
}
if ($enable) {
/* @var $rule UrlRule */
foreach ($this->rules as $rule) {
$result = $rule->parseRequest($this, $request);
if (YII_DEBUG) {
Yii::trace([
'rule' => method_exists($rule, '__toString') ? $rule->__toString() : get_class($rule),
'match' => $result !== false,
'parent' => null,
], __METHOD__);
}
if ($result !== false) {
return $result;
}
}
if ($this->enableStrictParsing) {
return false;
}
Yii::trace('No matching URL rules. Using default URL parsing logic.', __METHOD__);
$suffix = (string) $this->suffix;
$pathInfo = $request->getPathInfo();
$normalized = false;
if ($this->normalizer !== false) {
$pathInfo = $this->normalizer->normalizePathInfo($pathInfo, $suffix, $normalized);
}
if ($suffix !== '' && $pathInfo !== '') {
$n = strlen($this->suffix);
if (substr_compare($pathInfo, $this->suffix, -$n, $n) === 0) {
$pathInfo = substr($pathInfo, 0, -$n);
if ($pathInfo === '') {
// suffix alone is not allowed
return false;
}
} else {
// suffix doesn't match
return false;
}
}
if ($normalized) {
// pathInfo was changed by normalizer - we need also normalize route
return $this->normalizer->normalizeRoute([$pathInfo, []]);
}
return [$pathInfo, []];
}
Yii::trace('Pretty URL not enabled. Using default URL parsing logic.', __METHOD__);
$route = $request->getQueryParam($this->routeParam, '');
if (is_array($route)) {
$route = '';
}
return [(string) $route, []];
}
方法大多相同,不同之处在于前6行内。