dpgbh20688 2015-12-07 17:54 采纳率: 0%
浏览 26
已采纳

在启用漂亮网址后,Yii2旧链接无法正常工作

I'm currently updating an existing live website to use pretty urls. I've got the urls working, but my problem is that after I've enabled pretty urls all of the old links from sites like Google etc will stop working. They simply redirect to the front page. Examples; Old url: http://www.dreambulgarianproperties.com/index.php?r=properties%2Fproperty%2Fview&id=37 Redirects to the front page

New url: http://www.dreambulgarianproperties.com/properties/property/view?id=37 as it should look from both urls.

My .htaccess file is this:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule  ^(.*)$ index.php/$1

and my UrlManager config is this;

'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
        'enableStrictParsing' => false,
        'rules' => [
            '<action:\w+>' => 'site/<action>'
        ],
    ],

The site works fine, I'm just worried about losing Google traffic if I change the urls.

Is there a way of telling Yii to continue parsing old urls, while displaying and handling the new, pretty urls?

  • 写回答

2条回答 默认 最新

  • dongra1984 2015-12-08 05:25
    关注

    I found away to do this neatly. I extended the UrlManager and updated the parseRequest() method like this;

    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, []];
    }
    

    Now if there is a query string like index.php?r=controller/action it will process it, otherwise it passes control back to the parent UrlManager for normal processing.

    To keep my seo up to date I've added a canonical link in the header of every page so Google knows to use the pretty url for indexing.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部