Yii2 Url 美化重写 (pretty URLs / Seo friendly urls)urlManager管理

Yii2里面提供了我们修改路由规则的方法.

Yii2 Url 美化重写 (pretty URLs / Seo friendly urls)urlManager管理

方案1:

隐藏前后台web,Hide frontend/web and backend/web
Create .htaccess file on the root directory .
Options +FollowSymLinksRewriteEngine On
# End the processing, if a rewrite already occurred
RewriteRule ^(frontend|backend)/web/ - [L]
# Handle the case of backend, skip ([S=1]) the following rule, if current matched
RewriteRule ^backend(/(.*))?$ backend/web/$2 [S=1]
# handle the case of frontend
RewriteRule .* frontend/web/$0
# Uncomment the following, if you want speaking URL
#RewriteCond %{REQUEST_FILENAME} !-f
#RewriteCond %{REQUEST_FILENAME} !-d
#RewriteRule ^([^/]+/web)/.*$ $1/index.php
configure urlManager in your frontend/config/main.php and backend/config/main.php file.
//===前台config.php 'request'=>[
       'baseUrl'=>'',
],
'urlManager' => [
       'scriptUrl'=>'/',
],
//===后台config.php
'request'=>[ 'baseUrl'=>'/backend',
],
'urlManager'=>[
 'scriptUrl'=>'/backend/index.php',
],
路由美化规则:
'urlManager' => [
 'class' => 'yii\web\UrlManager',
 'enablePrettyUrl' => true,
 'showScriptName' => false,
 'rules' => array(
 '<controller:\w+>/<id:\d+>' => '<controller>/view',
 '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
 '<controller:\w+>/<action:\w+>' => '<controller>/<action>', 
 ),
],
增加.htaccess file into frontend/web backend/web folder
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php

Rewrite URL


'urlManager' => [           
           'class' => 'yii\web\UrlManager',
           'enablePrettyUrl' => true,
           'showScriptName' => false,
           'rules' => array(
             '<alias:\w+>' => 'site/<alias>', ///去掉首页site直接写出action
             '<controller:\w+>/<id:\d+>' => '<controller>/view',
             '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
             '<controller:\w+>/<action:\w+>' => '<controller>/<action>',  
             'cuisine' => 'site/cuisine',
             'range' => 'site/range',
             'collection' => 'site/collection',
             'cuisine/<cuisineid>' => 'site/foodgroup',
             'food_group/<cuisineid>/<foodgroupid>' => 'site/foodgroup',
             '2/<menu>/<id>' => 'site/bottle',
             '3/<menu>/<id>' => 'site/bottle',
             'page/<id>' => 'site/thebottle',
             'search/<keyword>' => 'site/search',
             'favoriten/<favorites>' => 'site/favoriten',
             '<lang>' => 'site/',
           ),
],
最后的结果
Sample User Friendly URL:
http://bottle.ch/frontend/web/index.php URL美化成 http://bottle.ch
http://bottle.ch/frontend/web/index.php?r=site/cuisine URL美化成 http://bottle.ch/cuisine
后台也一样.

方案2:

Yii2 SEO friendly URLs with extra parameters in PATH
'urlManager' => [
     'enablePrettyUrl' => true,
     'showScriptName' => false,
     //'urlFormat' => 'path',
       'rules' => [
           '<orgname:\w+>/<orgid:\d+>/<controller:\w+>/<id:\d+>' 
                   => '<controller>/view/<id>',
           '<orgname:\w+>/<orgid:\d+>/<controller:\w+>/<action:\w+>/<id:\d+>' 
                   => '<controller>/<action>',
           '<controller:\w+>/<id:\d+>' 
                   => '<controller>/view',
           '<controller:\w+>/<action:\w+>/<id:\d+>' 
                   => '<controller>/<action>',
           '<controller:\w+>/<action:\w+>' 
                   => '<controller>/<action>',
           '<action:\w+>' 
                   => 'site/<action>',
      ],
 ],


1. Extend Controller and put code in here to store org_id if present

 namespace frontend\components;
   
  use Yii;
  use yii\web\Controller;
  use common\models\Organization;
   
  /**
   * ActivityController implements the CRUD actions for Activity model.
   */
  class ZController extends Controller
  {
      
      public function init() {
          
          parent::init();
   
          if (Yii::$app->requestedRoute=='organization/view' || Yii::$app->getRequest()->getQueryParam('orgid')) {
              $id = (Yii::$app->requestedRoute=='organization/view') ? Yii::$app->getRequest()->getQueryParam('id') : Yii::$app->getRequest()->getQueryParam('orgid');
              $org = Organization::find($id)->asArray()->one();
              // make the name URL friendly
              $org = str_replace([' ','\'','"','-'],"_",$org);
              // store the data in params
              Yii::$app->params['organization_id'] = $id;
              Yii::$app->params['organization_name'] = $org['name'];
          }
          else
              Yii::$app->params['organization_id']=0;
          
      }
  }
2. Extend the URLManager

namespace app\components;
  
  use yii\web\UrlManager;
  use Yii;
   
  class XUrlManager extends UrlManager
  {
      public function createXUrl($params = [])
      {
          $params =(array) $params;
          // make sure we have all the data
          if (isset(Yii::$app->params['organization_id']) && isset(Yii::$app->params['organization_name']))
          {
              // grab the requested route
              $route=$params[0];
              // add on the bits we want org_name/org_id
              $route=Yii::$app->params['organization_name']."/".Yii::$app->params['organization_id']."/".$route;
              // put the new route back into array
              $params[0]=$route;
              // just in case, get rid of org_id from parameters in url eg: controller/action?orgid=x
              if (array_key_exists('orgid',$params))
              {
                  unset($params['orgid']);
              }
          }
          // call the regular urlManager
          $urlManager = Yii::$app->urlManager;
          return $urlManager->createUrl($params);
      }
  }
3. Call new URL manager
$url=XUrlManager::createXUrl('controller/action');

自定义URL样式(美化URL样式)



Previous Post电商广告图常用设计技巧剖析